In Java programming, some knowledge cannot be learned only through language specifications or standard API documentation. In this article, I will try to collect some of the most commonly used idioms, especially those that are difficult to guess. (Joshua Bloch's "Effective Java" gives a more detailed discussion on this topic, and you can learn more usage from this book.) I have made all the code in this article available in a public place. You can copy and modify any code snippet as you like, no credentials are required. Implementing equals()
The parameter must be of type Object and cannot be of a peripheral class. foo.equals(null) must return false and must not throw a NullPointerException. (Note that null instanceof any class always returns false, so the above code works.) Primitive type fields (such as int) are compared using ==, and primitive type array fields are compared using Arrays.equals(). When overriding equals(), remember to override hashCode() accordingly to be consistent with equals(). Reference: java.lang.Object.equals(Object). Implementing hashCode()
When two objects x and y have x.equals(y) == true , you must ensure that x.hashCode() == y.hashCode(). By contraposition, if x.hashCode() != y.hashCode(), then x.equals(y) == false must hold. You don't need to ensure that x.hashCode() != y.hashCode() when x.equals(y) == false. However, if you can make it as close to true as possible, it will improve the performance of your hash table. The simplest legal implementation of hashCode() is to simply return 0; while this implementation is correct, it will cause data structures such as HashMap to run very slowly. Reference: java.lang.Object.hashCode(). Implementing compareTo()
Always implement the generic version of Comparable instead of the original type Comparable, because it can save code and reduce unnecessary trouble. Only the sign (negative/zero/positive) of the returned result matters, their magnitude is not important. The implementation of Comparator.compare() is similar to this. Reference: java.lang.Comparable. #p# Implementing clone()
Use super.clone() to let the Object class be responsible for creating new objects. Primitive fields are correctly copied. Also, we don't need to clone immutable types like String and BigInteger. Manually deep copy all non-primitive fields (objects and arrays). For classes that implement Cloneable, the clone() method should never throw CloneNotSupportedException. Therefore, you need to catch this exception and ignore it, or wrap it with an unchecked exception. It is possible and legal to implement the clone() method manually instead of using Object.clone(). Reference: java.lang.Object.clone(), java.lang.Cloneable(). Using StringBuilder or StringBuffer
Do not use repeated string concatenation like this: s += item , as it is O(n^2) in time efficiency. When using StringBuilder or StringBuffer, you can use the append() method to add text and the toString() method to get the entire concatenated text. Prefer StringBuilder because it is faster. All methods of StringBuffer are synchronized, and you usually don't need synchronized methods. Refer to java.lang.StringBuilder, java.lang.StringBuffer. Generate a random integer in a range
Always use the Java API methods to generate a random number within an integer range. Do not try to use Math.abs(rand.nextInt()) % n, as the result is biased. In addition, the result may be negative, such as when rand.nextInt() == Integer.MIN_VALUE. Reference: java.util.Random.nextInt(int). Using Iterator.remove()
The remove() method acts on the entry most recently returned by the next() method. The remove() method can only be used once per entry. Reference: java.util.Iterator.remove(). Return string
This method should probably be added to the Java standard library. Reference: java.lang.StringBuilder.reverse(). Start a thread The following three examples use different methods to accomplish the same thing. How to implement Runnnable:
Inherit Thread method:
Anonymous inheritance of Thread:
Do not call the run() method directly. Always call the Thread.start() method, which creates a new thread and makes the newly created thread call run(). Reference: java.lang.Thread, java.lang.Runnable. #p# Using try-finally I/O stream example:
Lock example:
If the statement before the try fails and throws an exception, the finally block will not be executed. But in any case, there is no need to worry about releasing resources in this example. If the statement in the try block throws an exception, the program will jump to the finally block to execute as many statements as possible, and then jump out of the method (unless the method has another outer finally block). Read bytes from the input stream
The read() method either returns the next number of bytes to be read from the stream (0 to 255, inclusive), or returns -1 if the end of the stream is reached. Reference: java.io.InputStream.read(). Read chunks of data from an input stream
Keep in mind that the read() method will not necessarily fill the entire buf, so you must account for the returned length in your processing logic. Reference: java.io.InputStream.read(byte[]), java.io.InputStream.read(byte[], int, int). Reading text from a file
The creation of the BufferedReader object is lengthy because Java treats bytes and characters as two different concepts (which is different from C). 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 the Reader.read() method. You can use character encodings other than UTF-8, but you should not do so. Reference: java.io.BufferedReader, java.io.InputStreamReader. Writing text to a file
The creation of the Printwriter object is lengthy because Java treats bytes and characters as two different concepts (which is different from C). Just like System.out, you can use print() and println() to print values of many types. You can use character encodings other than UTF-8, but you should not do so. Reference: java.io.PrintWriter, java.io.OutputStreamWriter. Defensive checking value
Don't assume that input values are always positive, small enough, etc. Check these conditions explicitly. A well-designed function should perform correctly for all possible input values. It should ensure that all cases are considered and that no incorrect output (such as overflow) is produced. Preventive testing targets
Do not assume that object parameters will not be null. Check for this condition explicitly. #p# Preventive detection array index
Don't assume that any given array index will not be out of bounds. Check for it explicitly. Preventive detection of array intervals
Do not assume that a given array range (e.g., starting at off and reading len elements) will not go out of bounds. Check it explicitly. Filling array elements Using loops:
(Preferred) Method using the standard library:
Reference: java.util.Arrays.fill(T[], T). Reference: java.util.Arrays.fill(T[], int, int, T). Copies a range of array elements Using loops:
(Preferred) Method using the standard library:
Reference: java.lang.System.arraycopy(Object, int, Object, int, int). Resizing an Array Using a loop (scaling up):
Using a loop (reduced size):
(Preferred) Method using the standard library:
Reference: java.util.Arrays.copyOf(T[], int). Reference: java.util.Arrays.copyOfRange(T[], int, int). Packing 4 bytes into an int
Unpacking an int into 4 bytes
Always use the unsigned right shift operator (>>>) for packing bits, never the arithmetic right shift operator (>>). Original link: nayuki Translation: ImportNew.com - Jinlin Translation link: http://www.importnew.com/15605.html |
<<: Alibaba campus recruitment: Talking about interviews and interview questions
>>: Introduction to frequently used iOS third-party libraries and XCode plug-ins
1. Catering to user experience , information flow...
When users' content consumption needs extend ...
Since June this year, the State Administration of...
(Pictures are from the Internet) Mangoes are not ...
How much does a Tencent Video membership cost per...
From 1999 to 2023, from Shenzhou-1 to Shenzhou-17...
Data shows that Great Wall Motors sold 62,186 new...
On July 3, the Information Office of the Shandong...
[[416135]] People's Daily (Page 6, August 9, ...
[New Generation of Traders] The second issue of t...
Memories are irreplaceable. Money can buy a new T...
The Galaxy S8 was seen by DJ Koh, the head of Sam...
Since last year, the air purifier industry has sh...
1. Introduction Xiaobai: Dadongdong, can you help...