Java Classic Usage Summary _java

Source: Internet
Author: User
Tags comparable data structures

In Java programming, some knowledge is not only through the language specification or standard API documents can be learned, this article is listed.

First, realize

1, now 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 () {...}}

}

    • 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.) )
    • The 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 ().

2, now 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 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.

3. Realize CompareTo ()

Class Person implements comparable<person> {

 String firstName;

 String LastName;

 int birthdate;

 

 Compare by FirstName, break ties by LastName, finally break ties by birthdate public

 int CompareTo C6/>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;

 }

}

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.

4. Implement 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 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.

Second, the prevention of Detection

1, Preventive testing (defensive checking) value

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);

}

    • Don't assume that the values you enter are positive, small enough, and so on. You want to detect these conditions explicitly.
    • A well-designed function should be executed correctly for all possible input values. Make sure that all situations are considered and do not produce incorrect output (such as overflow).

2, the prevention of testing objects

int FindIndex (list<string> list, String target) {

 if (list = = NULL | | = TARGET = NULL)

  throw new Nullpointe Rexception ();

 ...

}

    • Do not consider object arguments to be empty (null). To detect this condition explicitly.

3, the preventive detection of array index

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 given array index does not cross. You want to detect it explicitly.

4. The range of preventive detection array

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 Indexoutofboundsexceptio n ();

 ...

}

Do not assume that the given array interval (for example, reading Len elements from off) is not crossed. You want to detect it explicitly.

Three, array

1. Filling array elements
Use loops:

Fill each element of the array ' a ' with 123

byte[] A = (...);

for (int i = 0; i < a.length i++)

 a[i] = 123;

(preferred) method of using the standard library:

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

2, copy a range of elements of the array
Use loops:

Copy 8 elements from array ' a ' starting in offset 3

//to array ' B ' starting at offset 6,

//assuming ' a ' and ' B ' are distinct arrays

byte[] A = (...);

Byte[] B = (...);

for (int i = 0; i < 8; i++)

 b[6 + i] = a[3 + i];

(preferred) methods for using the standard library:

system.arraycopy (A, 3, B, 6, 8);

3, adjust the size of the array
use loops (scaled up):

Make array ' a ' larger to Newlen

byte[] 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 (Decrease scale):

Make array ' a ' smaller to Newlen
byte[] 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) methods for using the standard library:

1a = arrays.copyof (A, Newlen);

4, the 4-byte packaging (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) <<;

}

5, the int decomposition (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) and do not use the arithmetic right shift operator (>>).

The above is the entire content of this article, I hope to help you learn.

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.