Detailed explanation of Java function idioms

In Java programming, some knowledge can not be learned only through language specifications or standard API documents. In this article, I try to collect some of the most common idioms, especially those that are hard to guess.

I put all the code for this article in a public place. You can copy and modify any code fragment according to your preference without any credentials.

Implement equals ()

The parameter must be of type object and cannot be a peripheral class.

foo. Equals (null) must return false and cannot throw NullPointerException. (note that null instanceof any class always returns false, so the above code can be run.)

The comparison of basic type fields (for example, int) uses = =, and the comparison of basic type array fields uses arrays equals()。

When overriding equals (), remember to override hashcode () accordingly, consistent with equals ().

Reference: Java lang.Object. equals(Object)。

Implement hashcode ()

When x and Y objects have x.equals (y) = = true, you must ensure that x.hashcode() = = y.hashcode().

According to the inverse proposition, if X. hashcode()= y. Hashcode(), then x.equals (y) = = false must be true.

You don't need to guarantee that when x.equals (y) = = false, x.hashcode()= y.hashCode()。 However, if you can make it as true as possible, it will improve the performance of the hash table.

The simplest legal implementation of hashcode() is simply to return 0; Although this implementation is correct, it will cause the data structures of HashMap to run very slowly.

Implement CompareTo ()

Always implement the generic version of comparable instead of the original type. Because this can save code and reduce unnecessary trouble.

Only the positive and negative signs (negative / zero / positive) of the returned results are concerned, and their size is not important.

Comparator. The implementation of compare () is similar to this.

Implement clone ()

Use super Clone () makes the object class responsible for creating new objects.

The basic type fields have been copied correctly. Similarly, we do not need to clone immutable types such as string and BigInteger.

Manually deep copy all non basic type fields (objects and arrays).

For classes that implement clonable, the clone () method should never throw clonenotsupportedexception. Therefore, you need to catch the exception and ignore it, or wrap it with an unchecked exception.

Do not use object It is possible and legal to implement the clone () method manually instead of the clone () method.

Use StringBuilder or StringBuffer

Do not use duplicate string connections like this: S + = item, because its time efficiency is O (n ^ 2).

When using StringBuilder or StringBuffer, you can use the append () method to add text and the toString () method to get the whole connected text.

StringBuilder is preferred because it is faster. All methods of StringBuffer are synchronized, and you usually don't need synchronized methods.

Generate a range of random integers

Always use Java API methods to generate a random number in the range of integers.

Don't try to use math ABS (rand. Nextint())% n these uncertain uses because its results are biased. In addition, its result value may be negative, such as when Rand nextInt() == Integer. MIN_ Value.

Use iterator remove()

The remove () method acts on the most recent entry returned by the next () method. The remove () method can only be used once per entry.

Return string

This method should probably be added to the Java standard library.

Start a thread

The following three examples do the same thing in different ways.

How to implement runnnable:

How to inherit thread:

How to inherit thread anonymously:

Do not call the run () method directly. Always call thread Start () method, which will create a new thread and make the new thread call run ().

Use try finally

I / O flow example:

Lock example:

If the statement before try fails and throws an exception, the finally statement block will not be executed. However, in this case, there is no need to worry about the release of resources.

If the statement in the try statement block throws an exception, the program will jump to the finally statement block, execute as many statements as possible, and then jump out of this method (unless this method has another peripheral finally statement block).

Read byte data from input stream

The read () method either returns the number of bytes (0 to 255, including 0 and 255) to be read from the stream next time, or returns - 1 when the end of the stream is reached.

Read block data from input stream

Remember that the read () method does not necessarily fill the entire buf, so you must consider the length of the return in the processing logic.

Read text from file

The creation of the BufferedReader object is lengthy. This is because Java treats bytes and characters as two different concepts (which is different from C language).

You can use any type of InputStream instead of FileInputStream, such as socket.

When the end of the stream is reached, BufferedReader Readline() returns null.

To read one character at a time, use reader Read() method.

You can use other character encoding instead of UTF-8, but it's best not to do so.

Write text to the file

The creation of the printwriter object appears lengthy. This is because Java treats bytes and characters as two different concepts (which is different from C language).

Like system Out, you can print multiple types of values using print () and println ().

You can use other character encoding instead of UTF-8, but it's best not to do so.

Preventive checking value

Don't think that all the entered values are positive numbers, small enough numbers, etc. To explicitly detect these conditions.

A well-designed function should execute correctly for all possible input values. Make sure that all situations are taken into account and do not produce incorrect output (such as overflow).

Preventive test object

Do not assume that the object parameter will not be null. To explicitly detect this condition.

Preventive detection array index

Do not assume that the given array index will not exceed the bounds. To explicitly detect it.

Preventive detection array interval

Don't think that the given array interval (for example, reading len elements from off) will not cross the boundary. To explicitly detect it.

Fill array elements

Use cycle:

(preferred) method of using standard library:

Arrays. fill(a,(byte)123);

Copy a range of array elements

Use cycle:

(preferred) method of using standard library:

System. arraycopy(a,3,b,6,8);

Resize array

Use cycle (scale up):

Use cycle (reduce scale):

(preferred) method of using standard library:

Pack four bytes into an int

Unpacking int into 4 bytes

Always use the unsigned shift right operator (> > >) to pack bits, not the arithmetic shift right operator (> >).

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>