楼主: NewOccidental
4040 18

Learning Java, 4th Edition [推广有奖]

  • 0关注
  • 6粉丝

已卖:1554份资源

副教授

31%

还不是VIP/贵宾

-

TA的文库  其他...

Complex Data Analysis

东西方金融数据分析

eBook with Data and Code

威望
0
论坛币
11734 个
通用积分
2.2450
学术水平
119 点
热心指数
115 点
信用等级
114 点
经验
8940 点
帖子
173
精华
10
在线时间
30 小时
注册时间
2006-9-19
最后登录
2022-11-3

楼主
NewOccidental 发表于 2015-4-12 06:28:51 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

Learning Java, 4th Edition

Book Description
Java is the preferred language for many of today's leading-edge technologies—everything from smartphones and game consoles to robots, massive enterprise systems, and supercomputers. If you're new to Java, the fourth edition of this bestselling guide provides an example-driven introduction to the latest language features and APIs in Java 6 and 7. Advanced Java developers will be able to take a deep dive into areas such as concurrency and JVM enhancements.

You'll learn powerful new ways to manage resources and exceptions in your applications, and quickly get up to speed on Java's new concurrency utilities, and APIs for web services and XML. You'll also find an updated tutorial on how to get started with the Eclipse IDE, and a brand-new introduction to database access in Java.
Book Details
  • Publisher:        O'Reilly Media
  • By:        Patrick Niemeyer, Daniel Leuck
  • ISBN:        978-1-44931-924-3
  • Year:        2013
  • Pages:        1010
  • Language:        English
  • File size:        25.7 MB
  • File format:        PDF
  • Download:       

    本帖隐藏的内容

    Learning Java, 4th Edition.pdf (24.55 MB, 需要: 20 个论坛币)




二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Learning Edition earning editio dition everything features provides systems latest

已有 2 人评分经验 学术水平 热心指数 信用等级 收起 理由
fantuanxiaot + 15 + 1 + 1 + 1 精彩帖子
xujingtang + 60 精彩帖子

总评分: 经验 + 75  学术水平 + 1  热心指数 + 1  信用等级 + 1   查看全部评分

本帖被以下文库推荐

沙发
charlmei(真实交易用户) 发表于 2015-4-16 06:02:14
StringBuilder and StringBuffer

In contrast to the immutable string, the java.lang.StringBuilder class is a modifiable and expandable buffer for characters. You can use it to create a big string efficiently. StringBuilder andStringBuffer are twins; they have exactly the same API. StringBuilder was added in Java 5.0 as a drop-in, unsynchronized replacement for StringBuffer. We’ll come back to that in a bit.

First, let’s look at some examples of String construction:

  1.     // Could be better
  2.     String ball = "Hello";
  3.     ball = ball + " there.";
  4.     ball = ball + " How are you?";
复制代码

This example creates an unnecessary String object each time we use the concatenation operator (+). Whether this is significant depends on how often this code is run and how big the string actually gets. Here’s a more extreme example:

   
  1. // Bad use of + ...
  2.     while( (line = readLine()) != EOF )
  3.         text += line;
复制代码

This example repeatedly produces new String objects. The character array must be copied over and over, which can adversely affect performance. The solution is to use a StringBuilder object and itsappend() method:

   
  1. StringBuilder sb = new StringBuilder("Hello");
  2.     sb.append(" there.");
  3.     sb.append(" How are you?");

  4.     StringBuilder text = new StringBuilder();
  5.     while( (line = readline()) != EOF )
  6.         text.append( line );
复制代码

Here, the StringBuilder efficiently handles expanding the array as necessary. We can get a String back from the StringBuilder with its toString() method:

  1.   String message = sb.toString();
复制代码

You can also retrieve part of a StringBuilder as a String by using one of the substring() methods.

You might be interested to know that when you write a long expression using string concatenation, the compiler generates code that uses a StringBuilder behind the scenes:

  1.   String foo = "To " + "be " + "or";
复制代码

It is really equivalent to:

    String foo = new      StringBuilder().append("To ").append("be ").append("or").toString();

In this case, the compiler knows what you are trying to do and takes care of it for you.

The StringBuilder class provides a number of overloaded append() methods for adding any type of data to the buffer. StringBuilder also provides a number of overloaded insert() methods for inserting various types of data at a particular location in the string buffer. Furthermore, you can remove a single character or a range of characters with the deleteCharAt() and delete() methods. Finally, you can replace part of the StringBuilder with the contents of a String using the replace() method. The String and StringBuilder classes cooperate so that, in some cases, no copy of the data has to be made; the string data is shared between the objects.

You should use a StringBuilder instead of a String any time you need to keep adding characters to a string; it’s designed to handle such modifications efficiently. You can convert the StringBuilder to a String when you need it, or simply concatenate or print it anywhere you’d use a String.

As we said earlier, StringBuilder was added in Java 5.0 as a replacement for StringBuffer. The only real difference between the two is that the methods of StringBuffer are synchronized and the methods of StringBuilder are not. This means that if you wish to use StringBuilder from multiple threads concurrently, you must synchronize the access yourself (which is easily accomplished). The reason for the change is that most simple usage does not require any synchronization and shouldn’t have to pay the associated penalty (slight as it is).

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

藤椅
fish0413(真实交易用户) 发表于 2015-4-18 12:36:18

String Methods

Method

Functionality


charAt()

Gets a particular character in the string


compareTo()

Compares the string with another string


concat()

Concatenates the string with another string


contains()

Checks whether the string contains another string


copyValueOf()

Returns a string equivalent to the specified character array


endsWith()

Checks whether the string ends with a specified suffix


equals()

Compares the string with another string


equalsIgnoreCase()

Compares the string with another string, ignoring case


getBytes()

Copies characters from the string into a byte array


getChars()

Copies characters from the string into a character array


hashCode()

Returns a hashcode for the string


indexOf()

Searches for the first occurrence of a character or substring in the string


intern()

Fetches a unique instance of the string from a global shared-string pool


isEmpty()

Returns true if the string is zero length


lastIndexOf()

Searches for the last occurrence of a character or substring in a string


length()

Returns the length of the string


matches()

Determines if the whole string matches a regular expression pattern


regionMatches()

Checks whether a region of the string matches the specified region of another string


replace()

Replaces all occurrences of a character in the string with another character


replaceAll()

Replaces all occurrences of a regular expression pattern with a pattern


replaceFirst()

Replaces the first occurrence of a regular expression pattern with a pattern


split()

Splits the string into an array of strings using a regular expression pattern as a delimiter


startsWith()

Checks whether the string starts with a specified prefix


substring()

Returns a substring from the string


toCharArray()

Returns the array of characters from the string


toLowerCase()

Converts the string to lowercase


toString()

Returns the string value of an object


toUpperCase()

Converts the string to uppercase


trim()

Removes leading and trailing whitespace from the string


valueOf()

Returns a string representation of a value


已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

板凳
vd671(未真实交易用户) 发表于 2015-5-16 11:19:12

Swing is Java’s graphical user interface toolkit. The javax.swing package (and its numerous subpackages) contain classes representing interface items such as windows, buttons, combo boxes, trees, tables, and menus—everything you need to build a modern, rich client-side application.

Swing is part of a larger collection of software called the Java Foundation Classes (JFC), which includes the following APIs:

  • The Abstract Window Toolkit (AWT), the original user interface toolkit and base graphics classes

  • Swing, the pure Java user interface toolkit

  • Accessibility, which provides tools for integrating nonstandard input and output devices into your user interfaces

  • The 2D API, a comprehensive set of classes for high-quality drawing

  • Drag and Drop, an API that supports the drag-and-drop metaphor



JFC is one of the largest and most complex parts of the standard Java platform, so it shouldn’t be any surprise that we’ll take several chapters to discuss it. In fact, we won’t even get to talk about all of it, just the most important parts—Swing and the 2D API.

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

报纸
hyq2003(未真实交易用户) 发表于 2015-5-16 15:10:48
  1. //file: ObserveImageLoad.java
  2.     import java.awt.*;
  3.     import java.awt.image.*;

  4.     public class ObserveImageLoad {

  5.       public static void main( String [] args)
  6.       {
  7.        ImageObserver myObserver = new ImageObserver() {
  8.           public boolean imageUpdate(
  9.              Image image, int flags, int x, int y, int width, int height)
  10.           {
  11.              if ( (flags & HEIGHT) !=0 )
  12.                System.out.println("Image height = " + height );
  13.              if ( (flags & WIDTH ) !=0 )
  14.                System.out.println("Image width = " + width );
  15.              if ( (flags & FRAMEBITS) != 0 )
  16.                System.out.println("Another frame finished.");
  17.              if ( (flags & SOMEBITS) != 0 )
  18.                 System.out.println("Image section :"
  19.                     + new Rectangle( x, y, width, height ) );
  20.              if ( (flags & ALLBITS) != 0 )
  21.                System.out.println("Image finished!");
  22.              if ( (flags & ABORT) != 0 )
  23.                System.out.println("Image load aborted...");
  24.              return true;
  25.          }
  26.        };

  27.         Toolkit toolkit = Toolkit.getDefaultToolkit();
  28.         Image img = toolkit.getImage( args[0] );
  29.         toolkit.prepareImage( img, -1, -1, myObserver );
  30.       }
  31.     }
复制代码

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

地板
zhujch(未真实交易用户) 发表于 2015-5-16 16:21:43

Drawing Animations

  1. Here is its source code:

  2.     //file: Hypnosis.java
  3.     import java.awt.*;
  4.     import java.awt.event.*;
  5.     import java.awt.geom.GeneralPath;
  6.     import javax.swing.*;

  7.     public class Hypnosis extends JComponent implements Runnable {
  8.       private int[] coordinates;
  9.       private int[] deltas;
  10.       private Paint paint;

  11.       public Hypnosis(int numberOfSegments) {
  12.         int numberOfCoordinates = numberOfSegments * 4 + 2;
  13.         coordinates = new int[numberOfCoordinates];
  14.         deltas = new int[numberOfCoordinates];
  15.         for (int i = 0 ; i < numberOfCoordinates; i++) {
  16.           coordinates[i] = (int)(Math.random() * 300);
  17.           deltas[i] = (int)(Math.random() * 4 + 3);
  18.           if (deltas[i] > 4) deltas[i] = -(deltas[i] - 3);
  19.         }
  20.         paint = new GradientPaint(0, 0, Color.BLUE,
  21.             20, 10, Color.RED, true);

  22.         Thread t = new Thread(this);
  23.         t.start();
  24.       }

  25.       public void run() {
  26.         try {
  27.           while (true) {
  28.             timeStep();
  29.             repaint();
  30.             Thread.sleep(1000 / 24);
  31.           }
  32.         }
  33.         catch (InterruptedException ie) {}
  34.       }

  35.       public void paint(Graphics g) {
  36.         Graphics2D g2 = (Graphics2D)g;
  37.         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  38.             RenderingHints.VALUE_ANTIALIAS_ON);
  39.         Shape s = createShape();
  40.         g2.setPaint(paint);
  41.         g2.fill(s);
  42.         g2.setPaint(Color.WHITE);
  43.         g2.draw(s);
  44.       }

  45.       private void timeStep() {
  46.         Dimension d = getSize();
  47.         if (d.width == 0 || d.height == 0) return;
  48.         for (int i = 0; i < coordinates.length; i++) {
  49.           coordinates[i] += deltas[i];
  50.           int limit = (i % 2 == 0) ? d.width : d.height;
  51.           if (coordinates[i] < 0) {
  52.             coordinates[i] = 0;
  53.             deltas[i] = -deltas[i];
  54.           }
  55.           else if (coordinates[i] > limit) {
  56.             coordinates[i] = limit - 1;
  57.             deltas[i] = -deltas[i];
  58.           }
  59.         }
  60.       }

  61.       private Shape createShape() {
  62.         GeneralPath path = new GeneralPath();
  63.         path.moveTo(coordinates[0], coordinates[1]);
  64.         for (int i = 2; i < coordinates.length; i += 4)
  65.           path.quadTo(coordinates[i], coordinates[i + 1],
  66.               coordinates[i + 2], coordinates[i + 3]);
  67.         path.closePath();
  68.         return path;
  69.       }

  70.       public static void main(String[] args) {
  71.         JFrame frame = new JFrame("Hypnosis");
  72.         frame.add( new Hypnosis(4) );
  73.         frame.setSize(300, 300);
  74.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  75.         frame.setVisible(true);
  76.       }
  77.     }
复制代码

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

7
pek2009(真实交易用户) 发表于 2015-5-16 18:05:58
Creating an Image

Let’s take a look at producing some image data. A picture is worth a thousand words, and, fortunately, we can generate a pretty picture in significantly fewer than a thousand words of Java. If we just want to render image frames byte by byte, you can put together a BufferedImage pretty easily.

The following application, ColorPan, creates an image from an array of integers holding RGB pixel values:

   
  1. //file: ColorPan.java
  2.     import java.awt.*;
  3.     import java.awt.image.*;
  4.     import javax.swing.*;

  5.     public class ColorPan extends JComponent {
  6.       BufferedImage image;

  7.       public void initialize() {
  8.         int width = getSize().width;
  9.         int height = getSize().height;
  10.         int[] data = new int [width * height];
  11.         int i = 0;
  12.         for (int y = 0; y < height; y++) {
  13.           int red = (y * 255) / (height - 1);
  14.           for (int x = 0; x < width; x++) {
  15.             int green = (x * 255) / (width - 1);
  16.             int blue = 128;
  17.             data[i++] = (red << 16) | (green << 8 ) | blue;
  18.           }
  19.         }
  20.         image = new BufferedImage(width, height,
  21.             BufferedImage.TYPE_INT_RGB);
  22.         image.setRGB(0, 0, width, height, data, 0, width);
  23.       }

  24.       public void paint(Graphics g) {
  25.         if (image == null)
  26.             initialize();
  27.         g.drawImage(image, 0, 0, this);
  28.       }

  29.       public void setBounds(int x, int y, int width, int height) {
  30.         super.setBounds(x,y,width,height);  
  31.         initialize();
  32.       }

  33.       public static void main(String[] args) {
  34.         JFrame frame = new JFrame("ColorPan");
  35.         frame.add(new ColorPan());
  36.         frame.setSize(300, 300);
  37.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  38.         frame.setVisible(true);
  39.       }
  40.     }
复制代码

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

8
JohnMason2013(未真实交易用户) 发表于 2015-5-16 19:29:29 来自手机
Updating a BufferedImage

BufferedImage can also be used to update an image dynamically. Because the image’s data arrays are directly accessible, you can simply change the data and redraw the picture whenever you want. This is probably the easiest way to build your own low-level animation software. The following example simulates the static on an old black-and-white television screen. It generates successive frames of random black and white pixels and displays each frame when it is complete. Figure 21-5 shows one frame of random static.

  1. Here’s the code:

  2.     //file: StaticGenerator.java
  3.     import java.awt.*;
  4.     import java.awt.event.*;
  5.     import java.awt.image.*;
  6.     import java.util.Random;
  7.     import javax.swing.*;

  8.     public class StaticGenerator extends JComponent implements Runnable {
  9.       byte[] data;
  10.       BufferedImage image;
  11.       Random random;

  12.       public void initialize() {
  13.         int w = getSize().width, h = getSize().height;
  14.         int length = ((w + 7) * h) / 8;
  15.         data = new byte[length];
  16.         DataBuffer db = new DataBufferByte(data, length);
  17.         WritableRaster wr = Raster.createPackedRaster(db, w, h, 1, null);
  18.         ColorModel cm = new IndexColorModel(1, 2,
  19.             new byte[] { (byte)0, (byte)255 },
  20.             new byte[] { (byte)0, (byte)255 },
  21.             new byte[] { (byte)0, (byte)255 });
  22.         image = new BufferedImage(cm, wr, false, null);
  23.         random = new Random();
  24.       }

  25.       public void run() {
  26.         if ( random == null )
  27.             initialize();
  28.         while (true) {
  29.           random.nextBytes(data);
  30.           repaint();
  31.           try { Thread.sleep(1000 / 24); }
  32.           catch( InterruptedException e ) { /* die */ }
  33.         }
  34.       }

  35.       public void paint(Graphics g) {
  36.         if (image == null) initialize();
  37.         g.drawImage(image, 0, 0, this);
  38.       }

  39.       public void setBounds(int x, int y, int width, int height) {
  40.         super.setBounds(x,y,width,height);
  41.         initialize();
  42.       }

  43.       public static void main(String[] args) {
  44.         //RepaintManager.currentManager(null).setDoubleBufferingEnabled(false);
  45.         JFrame frame = new JFrame("StaticGenerator");
  46.         StaticGenerator staticGen = new StaticGenerator();
  47.         frame.add( staticGen );
  48.         frame.setSize(300, 300);
  49.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  50.         frame.setVisible(true);
  51.         new Thread( staticGen ).start();
  52.       }
  53.     }
复制代码

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

9
斐斐斐(未真实交易用户) 发表于 2015-5-16 22:59:21
Filtering Image Data

An image filter is an object that performs transformations on image data. The Java 2D API supports image filtering through the BufferedImageOp interface. An image filter takes a BufferedImage as input (the source image) and performs some processing on the image data, producing another BufferedImage (the destination image).

  1. Here’s the source code:

  2.     //file: ImageProcessor.java
  3.     import java.awt.*;
  4.     import java.awt.event.*;
  5.     import java.awt.geom.*;
  6.     import java.awt.image.*;
  7.     import javax.swing.*;

  8.     public class ImageProcessor extends JComponent {
  9.       private BufferedImage source, destination;
  10.       private JComboBox options;

  11.       public ImageProcessor( BufferedImage image ) {
  12.         source = destination = image;
  13.         setBackground(Color.white);
  14.         setLayout(new BorderLayout());
  15.         // create a panel to hold the combo box
  16.         JPanel controls = new JPanel();
  17.         // create the combo box with the names of the area operators
  18.         options = new JComboBox(
  19.           new String[] { "[source]", "brighten", "darken", "rotate", "scale" }
  20.         );
  21.         // perform some processing when the selection changes
  22.         options.addItemListener(new ItemListener() {
  23.           public void itemStateChanged(ItemEvent ie) {
  24.             // retrieve the selection option from the combo box
  25.             String option = (String)options.getSelectedItem();
  26.             // process the image according to the selected option
  27.             BufferedImageOp op = null;
  28.             if (option.equals("[source]"))
  29.               destination = source;
  30.             else if (option.equals("brighten"))
  31.               op = new RescaleOp(1.5f, 0, null);
  32.             else if (option.equals("darken"))
  33.               op = new RescaleOp(.5f, 0, null);
  34.             else if (option.equals("rotate"))
  35.               op = new AffineTransformOp(
  36.                   AffineTransform.getRotateInstance(Math.PI / 6), null);
  37.             else if (option.equals("scale"))
  38.               op = new AffineTransformOp(
  39.                   AffineTransform.getScaleInstance(.5, .5), null);
  40.             if (op != null) destination = op.filter(source, null);
  41.             repaint();
  42.           }
  43.         });
  44.         controls.add(options);
  45.         add(controls, BorderLayout.SOUTH);
  46.       }

  47.       public void paintComponent(Graphics g) {
  48.         int imageWidth = destination.getWidth();
  49.         int imageHeight = destination.getHeight();
  50.         int width = getSize().width;
  51.         int height = getSize().height;
  52.         g.drawImage(destination,
  53.             (width - imageWidth) / 2, (height - imageHeight) / 2, null);
  54.       }

  55.       public static void main(String[] args) {
  56.         String filename = args[0];

  57.         ImageIcon icon = new ImageIcon(filename);
  58.         Image i = icon.getImage();

  59.         // draw the Image into a BufferedImage
  60.         int w = i.getWidth(null), h = i.getHeight(null);
  61.         BufferedImage buffImage = new BufferedImage(w, h,
  62.             BufferedImage.TYPE_INT_RGB);
  63.         Graphics2D imageGraphics = buffImage.createGraphics();
  64.         imageGraphics.drawImage(i, 0, 0, null);

  65.         JFrame frame = new JFrame("ImageProcessor");
  66.         frame.add(new ImageProcessor(buffImage));
  67.         frame.setSize(buffImage.getWidth(), buffImage.getHeight());
  68.         frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  69.         frame.setVisible(true);
  70.       }
  71.     }
复制代码

10
力大骆驼(未真实交易用户) 发表于 2015-5-17 00:07:04
Using the AffineTransformOp Class

An affine transformation is a kind of 2D transformation that preserves parallel lines; this includes operations like scaling, rotating, and shearing. The java.awt.image.AffineTransformOp image operator geometrically transforms a source image to produce the destination image. To create an AffineTransformOp, specify the transformation you want in the form of an java.awt.geom.AffineTransform. TheImageProcessor application includes two examples of this operator, one for rotation and one for scaling. As before, the AffineTransformOp constructor accepts a set of hints; we’ll just pass null to keep things simple:

  1.     else if (option.equals("rotate"))
  2.       op = new AffineTransformOp(
  3.           AffineTransform.getRotateInstance(Math.PI / 6), null);
  4.     else if (option.equals("scale"))
  5.       op = new AffineTransformOp(
  6.           AffineTransform.getScaleInstance(.5, .5), null);
复制代码

In both cases, we obtain an AffineTransform by calling one of its static methods. In the first case, we get a rotational transformation by supplying an angle. This transformation is wrapped in anAffineTransformOp. This operator has the effect of rotating the source image around its origin to create the destination image. In the second case, a scaling transformation is wrapped in anAffineTransformOp. The two scaling values, .5 and .5, specify that the image should be reduced to half its original size in both the x and y axes.

When using an AffineTransformOp to scale images, it’s important to note two things. Scaling an image up will always result in poor quality. When scaling an image down, and more generally with any affine transform, you can choose between speed and quality. Using AffineTransformOp.TYPE_NEAREST_NEIGHBOR as the second argument in your AffineTransformOp constructor will give you speed. For the best quality use AffineTransformOp.TYPE_BICUBIC. AffineTransformOp.TYPE_BILINEAR balances speed and quality.

One interesting aspect of AffineTransformOp is that you may “lose” part of your image when it’s transformed. For example, when using the rotate image operator in the ImageProcessor application, the destination image will have clipped some of the original image out. Both the source and destination images have the same origin, so if any part of the image gets transformed into negative x or y space, it is lost. To work around this problem, you can structure your transformations such that the entire destination image is in positive coordinate space.

已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2025-12-31 05:19