Java idiomatic usage

Source: Internet
Author: User

Http://www.admin10000.com/document/6157.html
    • Realize:
      • Equals ()
      • Hashcode ()
      • CompareTo ()
      • Clone ()
    • Application:
      • Stringbuilder/stringbuffer
      • Random.nextint (int)
      • Iterator.remove ()
      • Stringbuilder.reverse ()
      • Thread/runnable
      • Try-finally
    • Input/output:
      • Reading byte data from the input stream
      • Reading block data from the input stream
      • Read text from a file
      • Write text to a file
    • Preventative testing:
      • Numerical
      • Object
      • Array index
      • Array interval
    • Array:
      • Fill element
      • To copy an array element in a range
      • Resizing an array
    • Packaging
      • A byte is wrapped in an int
      • Break down into 4 bytes

Implement Equals ()
Class Person {  String name;  int birthyear;  Byte[] Raw;  public boolean equals (Object obj) {    if (!obj instanceof person)      return false;    person other = (person) obj;    Return Name.equals (other.name)        && birthyear = = Other.birthyear        && arrays.equals (Raw, Other.raw);  }  public int hashcode () {...}}
    • The parameter must be of type object and cannot be a perimeter 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 run.) )
    • The comparison of the base type fields (for example, int) uses = =, and the comparison of the primitive type array fields 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;  byte C;  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 make sure that x.hashcode () = = Y.hashcode ().
    • According to the inverse 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 easy as possible, this will improve the performance of the hash table.
    • The simplest legal implementation of hashcode () is simply return 0, although the implementation is correct, but this results in hashmap these data structures running slowly.
    • Reference: Java.lang.Object.hashCode ().

Implement CompareTo ()
Class Person implements comparable<person> {  String firstName;  String LastName;  int birthdate;  Compare by FirstName, breaks ties by LastName, finally breaks ties by birthdate public  int CompareTo (person other) { C5/>if (Firstname.compareto (other.firstname)! = 0)      return Firstname.compareto (other.firstname);    else if (Lastname.compareto (other.lastname)! = 0)      return Lastname.compareto (other.lastname);    else if (Birthdate < other.birthdate)      return-1;    else if (Birthdate > Other.birthdate)      return 1;    else      return 0;}  }
    • The generic version comparable is always implemented instead of implementing the original type comparable. Because it saves code and reduces unnecessary hassles.
    • Only concerns the sign of the returned result (negative/0/positive), their size is not important.
    • The implementation of Comparator.compare () is similar to this.
    • Reference: Java.lang.Comparable.

Implementing Clone ()
Class Values implements cloneable {  String abc;  Double foo;  Int[] Bars;  Date hired;  Public Values Clone () {    try {      values result = (values) super.clone ();      Result.bars = Result.bars.clone ();      result.hired = Result.hired.clone ();      return result;    } catch (Clonenotsupportedexception e) {  //impossible      throw new Assertionerror (e);    }  }
    • Use Super.clone () to have the object class responsible for creating new objects.
    • The base type fields have been copied correctly. Again, we do not need to clone the immutable types such as String and BigInteger.
    • Deep copy of all non-basic type fields (objects and arrays) are manually made.
    • Implements the Cloneable class, and the Clone () method never throws Clonenotsupportedexception. Therefore, you need to catch the exception and ignore it, or wrap it with no exception (unchecked exception).
    • It is also legal to implement the Clone () method manually rather than using the Object.clone () method.
    • 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 = new Stringbuil Der ();  Boolean first = true;  for (String s:strs) {    if (first) First first = false;    Else Sb.append ("and");    Sb.append (s);  }  return sb.tostring ();}
    • 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 use the ToString () method to get the entire concatenated text.
    • Prefer to use StringBuilder because it is faster. All methods of StringBuffer are synchronous, and you do not normally need to synchronize the methods.
    • Refer to Java.lang.StringBuilder, Java.lang.StringBuffer.

Generate a random integer in a range
Random rand = new Random ();//between 1 and 6, Inclusiveint Diceroll () {  return Rand.nextint (6) + 1;}
    • Always use the Java API method to generate a random number within an integer range.
    • Do not attempt to use Math.Abs (Rand.nextint ())% n These indeterminate usages, because the result of it 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 last entry returned by the next () method. You can use the Remove () method only once for each entry.
    • Reference: Java.util.Iterator.remove ().

return string
String reverse (string s) {  return new StringBuilder (s). Reverse (). ToString ();}
    • This method may 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 implement Runnnable:

void StartAThread0 () {  new Thread (New Myrunnable ()). Start (); Class Myrunnable implements Runnable {public  void run () {    ...  }}

How to inherit thread:

void StartAThread1 () {  new MyThread (). Start (); Class MyThread extends Thread {public  void run () {    ...  }}

How to inherit thread anonymously:

void StartAThread2 () {  new Thread () {public    void run () {      ...    }  }. Start ();}
    • Do not call the run () method directly. Always call the Thread.Start () method, which creates a new thread and causes the newly created thread to call run ().
    • Reference: Java.lang.Thread, java.lang.Runnable.

Using try-finally

Examples of I/O streams:

void Writestuff () throws IOException {  OutputStream out = new FileOutputStream (...);  try {    out.write (...);  } finally {    out.close ()}  }

Lock Example:

void Dowithlock (Lock lock) {  lock.acquire ();  try {    ...  } finally {    lock.release ();}  }
    • If the statement before the try fails and throws an exception, then the finally statement block is not executed. However, in this case there is no need to worry about the release of resources.
    • If the statement inside the try statement block throws an exception, the program's run jumps to the finally statement block to execute as many statements as possible, and then jumps out of the way (unless the method has another finally block of the surface).

Reading byte data from the input stream
InputStream in = (...); try {  while (true) {    int b = In.read ();    if (b = =-1) break      ;    (.... process b ...)  }} finally {  in.close ();}
    • The read () method either returns the next number of bytes read from the stream (0 to 255, including 0 and 255), or returns-1 when the end of the stream is reached.
    • Reference: Java.io.InputStream.read ().

Reading block data from the input stream
InputStream in = (...); try {  byte[] buf = new byte[100];  while (true) {    int n = in.read (BUF);    if (n = =-1) break      ;    (.... process buf with offset=0 and length=n ...)  }} finally {  in.close ();}
    • Keep in mind that the read () method does not necessarily fill the entire buf, so you must consider the length of the return in the processing logic.
    • Reference: Java.io.InputStream.read (byte[]), Java.io.InputStream.read (byte[], int, int).

Read text from a file
BufferedReader in = new BufferedReader (    new InputStreamReader (New FileInputStream (...), "UTF-8")), try {while  ( true) {    String line = In.readline ();    if (line = = null) break      ;    (.... Process line ...)  }} finally {  in.close ();}
    • The creation of BufferedReader objects is lengthy. This is because Java treats bytes and characters as two different concepts (this differs from the C language).
    • You can use any type of inputstream instead of FileInputStream, such as a 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 other character encodings instead of using UTF-8, but it's best not to do so.
    • Reference: Java.io.BufferedReader, Java.io.InputStreamReader.

Write text to a file
PrintWriter out = new PrintWriter (New    OutputStreamWriter (New FileOutputStream (...), "UTF-8")), try {  Out.print ("Hello");  Out.print (a);  Out.println ("world!");} finally {  out.close ();}
    • The creation of PrintWriter objects is lengthy. This is because Java treats bytes and characters as two different concepts (this differs from the C language).
    • Like System.out, you can use print () and println () for printing multiple types of values.
    • You can use other character encodings instead of using UTF-8, but it's best not to do so.
    • Reference: Java.io.PrintWriter, Java.io.OutputStreamWriter.

Preventive testing (defensive checking) values
int factorial (int n) {  if (n < 0)    throw new IllegalArgumentException ("Undefined");  else if (n >=)    throw new ArithmeticException ("Result Overflow");  else if (n = = 0)    return 1;  else    return n * factorial (n-1);}
    • Do not assume that the input values are positive, small enough, and so on. To explicitly detect these conditions.
    • A well-designed function should be executed correctly for all possible input values. Make sure that all situations are taken into account and that no incorrect output (such as overflow) is generated.

Preventive Test Object
int FindIndex (list<string> list, String target) {  if (list = = NULL | | target = = NULL)    throw new Nullpointe Rexception ();  ...}
    • Do not assume that the object parameter is not empty (null). To explicitly detect this condition.

Predictive array index for preventive testing
void Frob (byte[] B, int index) {  if (b = = null)    throw new NullPointerException ();  if (Index < 0 | | index >= b.length)    throw new Indexoutofboundsexception ();  ...}
    • Do not assume that the array index given is not out of bounds. to explicitly detect it.

Preventive detection of array intervals
void Frob (byte[] b, int off, int len) {  if (b = = null)    throw new NullPointerException ();  if (Off < 0 | | off > b.length    | | Len < 0 | | B.length-off < len)    throw new Indexoutofboundsexception ();  ...}
    • Do not assume that the given array interval (for example, starting from off, reading Len elements) is not out of bounds. to explicitly detect it.

Populating array elements

Using loops:

Fill each element of the array ' a ' with 123byte[] a = (...); for (int i = 0; i < a.length; i++)  a[i] = 123;

(preferred) The method of using the standard library:

Arrays.fill (A, (byte) 123);
    • Reference: Java.util.Arrays.fill (t[], T).
    • Reference: Java.util.Arrays.fill (t[], int, int, T).

To copy an array element in a range

Using loops:

Copy 8 elements from array ' a ' starting @ Offset 3//to array ' B ' starting at offset 6,//assuming ' a ' and ' B ' is dis Tinct arraysbyte[] A = (...); Byte[] B = (...); for (int i = 0; i < 8; i++)  b[6 + i] = a[3 + i];

(preferred) The method of using the standard library:

System.arraycopy (A, 3, B, 6, 8);
    • Reference: Java.lang.System.arraycopy (object, int, object, int, int).

Resizing an array

Use loops (enlarge scale):

Make array ' a ' larger to newlenbyte[] a = (...); Byte[] B = new Byte[newlen];for (int i = 0; i < a.length; i++)  //Goes up to length of a  b[i] = A[i];a = b;

Use loops (reduce scale):

Make array ' a ' smaller to newlenbyte[] a = (...); Byte[] B = new Byte[newlen];for (int i = 0; i < b.length; i++)  //Goes up to length of B  b[i] = A[i];a = b;

(preferred) The method of using the standard library:

A = Arrays.copyof (A, Newlen);
    • Reference: Java.util.Arrays.copyOf (t[], int).
    • Reference: Java.util.Arrays.copyOfRange (t[], int, int).

Wrap 4 bytes (packing) into an int
int Packbigendian (byte[] b) {  return (B[0] & 0xFF) <<       | (B[1] & 0xFF) <<       | (B[2] & 0xFF) <<  8       | (B[3] & 0xFF) <<  0;} int Packlittleendian (byte[] b) {  return (B[0] & 0xFF) <<  0       | (B[1] & 0xFF) <<  8       | (B[2] & 0xFF) <<       | (B[3] & 0xFF) << 24;}

divide int (unpacking) into 4 bytes
Byte[] Unpackbigendian (int x) {  return new byte[] {    (byte) (x >>>),    (Byte) (x >>> +), 
    (Byte) (x >>>  8),    (Byte) (x >>>  0)  }; Byte[] Unpacklittleendian (int x) {  return new byte[] {    (byte) (x >>>  0),    (Byte) (x >> >  8), (    byte) (x >>> +),    (Byte) (x >>>)  };
    • Always use the unsigned Right shift operator (>>>) to wrap bits (packing), instead of using the arithmetic right shift operator (>>).

Java idiomatic usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.