In Java programming, some knowledge cannot be learned only through language specifications or standard API documentation. In this article, I'll try to collect some of the most common idioms, especially those that are hard to guess. (Joshua Bloch's "effective Java" gives a more detailed account of this topic, and can learn more from this book.) )
I put all the code in this article in public places. You can copy and modify arbitrary snippets of code according to your preferences, and you don't need any credentials. directory implementation: Equals () Hashcode () CompareTo () Clone () Application: Stringbuilder/stringbuffer random.nextint (int) Iterator.remove () stringbuilder.reverse () thread/runnable try-finally input/output: Reading byte data from input stream reading block data from the input stream reading text from a file to writing text to a file Preventative detection: Array of numeric objects array index arrays: Fill elements Copy an array element in a range resize the array to wrap a byte into an int and break it into 4 bytes.
implement Equals ()
Class Person {
String name;
int birthyear;
Byte[] Raw;
public boolean equals (Object obj) {
if (!obj Instanceofperson) return
false;
person other = (person) obj;
Return Name.equals (other.name)
&& birthyear = other.birthyear
&& arrays.equals (Raw, Other.raw);
}
public int hashcode () {...}}
}
Parameter must be of type object and cannot be a peripheral class. Foo.equals (NULL) must return FALSE, NullPointerException cannot be thrown. (Note that null instanceof any class always returns false, so the above code can run.) A comparison of the base type field (for example, int) uses = =, and the comparison of the base type array field uses Arrays.equals (). When overriding Equals (), remember to overwrite hashcode () Accordingly, consistent with equals (). Reference: Java.lang.Object.equals (Object).
implement Hashcode ()
Class Person {
String A;
Object b;
Bytec;
Int[] D;
public int hashcode () {return
A.hashcode () + b.hashcode () + C + arrays.hashcode (d);
}
public boolean equals (Object o) {...}
}
When X and y two objects have x.equals (y) = = True, you must ensure that x.hashcode () = = Y.hashcode (). According to the converse proposition, if X.hashcode ()!= y.hashcode (), then x.equals (y) = = false must be true. You do not need to guarantee that when x.equals (y) = = False, X.hashcode ()!= Y.hashcode (). However, if you can make it as effective as possible, this will improve the performance of the hash table. Hashcode () The simplest legal implementation is simply to return 0, although this implementation is correct, but this results in a slow hashmap of these data structures. Reference: Java.lang.Object.hashCode ().
implement CompareTo ()
Class person implementscomparable<person> {
String firstName;
String LastName;
Intbirthdate;
Compare by FirstName, break ties by LastName, finally break ties by birthdate public
int CompareTo C5/>if (Firstname.compareto (other.firstname)!= 0)
Returnfirstname.compareto (other.firstname);
else if (Lastname.compareto (other.lastname)!= 0)
Returnlastname.compareto (other.lastname);
else if (Birthdate < other.birthdate)
return-1;
else if (Birthdate > Other.birthdate)
return1;
else
return0;
}
}
Always implement generic version comparable instead of implementing the original type comparable. This can save code and reduce unnecessary hassle. Only the positive sign (minus/0/positive) of the returned result is concerned, and their size is unimportant. The implementation of Comparator.compare () is similar to this one. Reference: Java.lang.Comparable.
Implementing Clone ()
Class Values implementscloneable {
String abc;
Doublefoo;
Int[] Bars;
Date hired;
Public values Clone () {
try{
values result = (values) super.clone ();
Result.bars = Result.bars.clone ();
result.hired = Result.hired.clone ();
Returnresult;
} catch (Clonenotsupportedexception e) { //Impossible
thrownew Assertionerror (e);
}
}}
Use Super.clone () to make the object class responsible for creating new objects. The base type fields have been copied correctly. Again, we do not need to clone string and BigInteger immutable types. Manually make a deep copy of all non-basic type fields (objects and arrays) (deep copy). Implements the Cloneable class, The Clone () method never throws Clonenotsupportedexception. Therefore, you need to catch this exception and ignore it, or wrap it with a unchecked exception (exception). The manual implementation of the Clone () method without using the Object.clone () method can and is legal. Reference: Java.lang.Object.clone (), java.lang.Cloneable ().
using StringBuilder or StringBuffer
Join (["A", "B", "C"])-> "A and B and C"
String join (list<string> strs) {
StringBuilder sb = newstring Builder ();
Booleanfirst = true;
for (String s:strs) {
if (a): false;
Elsesb.append ("and");
Sb.append (s);
}
Returnsb.tostring ();
}
Do not use duplicate string concatenation 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 use the ToString () method to get the entire text connected. Prioritize the use of StringBuilder because it's faster. All methods of StringBuffer are synchronized, and you usually do not need to synchronize the methods. Refer to Java.lang.StringBuilder, Java.lang.StringBuffer.
generates a range of random integers
Random rand = Newrandom ();
Between 1 and 6, inclusive
Intdiceroll () {return
Rand.nextint (6) + 1;
}
Always use the Java API method to generate a random number in the range of integers. Do not attempt to use Math.Abs (Rand.nextint ())% n These indeterminate uses, because the result is biased. In addition, its result value may be negative, such as when rand.nextint () = = Integer.min_value. Reference: java.util.Random.nextInt (int).
using Iterator.remove ()
void filter (List<string> List) {for
(iterator<string> iter = List.iterator (); Iter.hasnext ();) {
String item = Iter.next ();
if (...)
Iter.remove ();
}
The Remove () method acts on the item that is recently returned by the next () method. You can only use the Remove () method once per entry. Reference: Java.util.Iterator.remove ().
return String
String reverse (string s) {return
new StringBuilder (s). Reverse (). toString ();
}
This method might be added to the Java Standard library. Reference: Java.lang.StringBuilder.reverse ().
Start a thread
The following three examples use different ways to accomplish the same thing.
Ways to achieve runnnable:
void StartAThread0 () {
new Thread (Newmyrunnable ()). Start ();
Class myrunnable implementsrunnable {public
void run () {
...}}
}
How to inherit thread:
void StartAThread1 () {
new Mythread (). Start ();
Class Mythread Extendsthread {public
void run () {
...}}
}
How to inherit thread anonymously:
void StartAThread2 () {
new Thread () {
publicvoid run () {
...}}
}. Start ();
}
Do not call the run () method directly. Always call the Thread.Start () method, which creates a new thread and makes the new thread call run (). Reference: Java.lang.Thread, java.lang.Runnable.
using try-finally
I/O Flow example:
void Writestuff () throwsioexception {
OutputStream out = Newfileoutputstream (...);
try{
out.write (...);
} finally{
out.close ();
}
Lock Example:
void Dowithlock (Lock lock) {
lock.acquire ();
try{...
} finally{
lock.release ();
}