Java Basics--some common methods for object

Source: Internet
Author: User

equals (Object obj): Determines whether two objects are the same (the string class overrides the method)

1. The difference between equals () and = =

    • For the base type, = = Determines whether two values are equal and the base type does not have the Equals () method.
    • For reference types, = = Determines whether two instances refer to the same object, and Equals () determines whether the referenced object is equivalent.
New Integer (1new integer (1//  trueSystem.out.println (x = = y);      // false

The 2.equals () method implements an equality relationship on a non-null object reference:

//reflexive NatureX.equals (x);//true//symmetry ofX.equals (y) = = y.equals (x)//true//transitivityif(X.equals (y) &&y.equals (z)) {x.equals (z);//true;}//consistency: Calling the Equals () method multiple times results unchangedX.equals (y) = = X.equals (y);//true//comparison with null: for any non-null object xX.euqals (NULL);//false;

3. Implement

    • Checks whether a reference to the same object, if true, is returned directly;
    • Check whether the same type, if not, returns false directly;
    • Transforming an Object instance;
    • Determines whether each key field is equal.
 Public classEqualexample {Private intx; Private inty; Private intZ;  PublicEqualexample (intXintYintz) { This. x =x;  This. y =y;  This. z =Z; } @Override Public Booleanequals (Object o) {if( This= = O)return true; if(O = =NULL|| GetClass ()! = O.getclass ())return false; Equalexample that=(equalexample) o; if(x! = that.x)return false; if(Y! = that.y)return false; returnz = =that.z; }}

Hashcode (): Returns the hash value of an object

Hashcode () is a native method, and the return value type is integer; in fact, the native method returns the address of the object in memory as a hash code, which guarantees that the return value of the different objects is different. The same hash value is not equal to the instance, and two equal instance hash values must be the same.

The role of the Hashcode () method in the JDK, as well as considerations for implementation, are explained:

    • Hashcode () functions in a hash table, such as Java.util.HashMap;

    • If the information used by the object in Equals () has not changed, then the Hashcode () value is always the same;

    • If two objects are judged equal using the Equals () method, the Hashcode () method should also be equal;

    • If two objects are judged to be unequal using the Equals () method, then hashcode () must not be required to be unequal, but developers should realize that unequal objects produce different hashcode to improve the performance of the hash table.

the role of Hashcode ():

In general, Hashcode () works in a hash table, such as HashSet, HashMap, and so on.

When we add object objects to a hash table (such as HashSet, HashMap, and so on), we first call the Hashcode () method to calculate the hash code of object, and the hash code allows you to directly position the location of object in the hash table (typically hash code is redundant to the Hashtable size). If there are no objects at that location, you can insert the object directly into that position, and if there are objects (possibly multiple, through the linked list), the Equals () method is called to compare the objects to object equality, and if they are equal, no object is required; The object is added to the linked list.

This also explains why Equals () is equal, and hashcode () must be equal. If two objects equals () are equal, they should only occur once in a hash table (such as HashSet, HashMap, and so on), and if hashcode () are unequal, they will be hashed to different locations in the hash table, more than once.

In fact, in the JVM, the loaded object consists of three parts in memory: The object header, the instance data, and the padding. The object header includes a pointer to the type of the object and Markword, while the Markword contains the object's GC generational age information, the lock state information, but also includes the object's Hashcode; object instance data is a valid information that the object is actually stored The fill part only acts as a placeholder because the hotspot requires that the object start address must be an integer multiple of 8 bytes.

toString (): [email protected] is returned by default, where the value after @ is the unsigned hexadecimal representation of the hash code.

 Public class tostringexample {    privateint number ;      Public Tostringexample (int number ) {        this. Number = number ;    }} 

New Tostringexample (123); System.out.println (Example.tostring ());
// [email protected]

Clone (): The protected method of Object, which means that there is no such method if a class does not explicitly override Clone ().

1.cloneable

 Public class cloneexample {    privateint  A;     Private int b;}

New//  ' Clone () ' have protected access in ' Java.lang.Object '

Next, the Clone () that covers Object is implemented as follows:

 public  class   cloneexample { private  int   A;  private  int      b; @Override  protected  cloneexample Clone ()  Throws   clonenotsupportedexception {     return  (cloneexample) super  .clone (); }}
New cloneexample (); Try {    =catch  (clonenotsupportedexception e) {    e.printstacktrace ();}
java.lang.CloneNotSupportedException: Cloneexample

The above code throws a clonenotsupported exception because Cloneexample does not implement the Cloneable interface.

 Public class Implements cloneable {    privateint  A;     Private int b;    @Override    protectedthrows  clonenotsupportedexception {          ReturnSuper. Clone ();}    }

It should be noted that the Clone () method is not a cloneable interface method, but a protected method of Object. The cloneable interface simply stipulates that if a class does not implement the Cloneable interface and invokes the Clone () method, it throws clonenotsupportedexception.

2. Deep copy and shallow copy

    • Shallow copy: The reference type of the copy instance and the original instance refers to the same object;
    • Deep copy: The reference type of the copy instance and the original instance refers to different objects.
 Public classShallowcloneexampleImplementscloneable {Private int[] arr;  Publicshallowcloneexample () {arr=New int[10];  for(inti = 0; i < arr.length; i++) {Arr[i]=i; }    }     Public voidSetintIndexintvalue) {Arr[index]=value; }     Public intGetintindex) {        returnArr[index]; } @OverrideprotectedShallowcloneexample Clone ()throwsclonenotsupportedexception {return(shallowcloneexample)Super. Clone (); }}
Newnull; Try {    =catch  (clonenotsupportedexception e) {    e.printstacktrace ();} E1.set (2, 222); System.out.println (E2.get (//  222

 Public classDeepcloneexampleImplementscloneable {Private int[] arr;  Publicdeepcloneexample () {arr=New int[10];  for(inti = 0; i < arr.length; i++) {Arr[i]=i; }    }     Public voidSetintIndexintvalue) {Arr[index]=value; }     Public intGetintindex) {        returnArr[index]; } @OverrideprotectedDeepcloneexample Clone ()throwsclonenotsupportedexception {deepcloneexample result= (deepcloneexample)Super. Clone (); Result.arr=New int[Arr.length];  for(inti = 0; i < arr.length; i++) {Result.arr[i]=Arr[i]; }        returnresult; }}
Newnull; Try {    =catch  (clonenotsupportedexception e) {    e.printstacktrace ();} E1.set (2, 222); System.out.println (E2.get (//  2

Copying an object using the Clone () method is complex and risky, throws an exception, and requires a type conversion. Effective Java book, it is best not to use Clone (), you can use copy constructor or copy factory to copy an object.

 Public classCloneconstructorexample {Private int[] arr;  Publiccloneconstructorexample () {arr=New int[10];  for(inti = 0; i < arr.length; i++) {Arr[i]=i; }    }     Publiccloneconstructorexample (cloneconstructorexample original) {arr=New int[Original.arr.length];  for(inti = 0; i < original.arr.length; i++) {Arr[i]=Original.arr[i]; }    }     Public voidSetintIndexintvalue) {Arr[index]=value; }     Public intGetintindex) {        returnArr[index]; }}

Newnew  cloneconstructorexample (E1); E1.set (2, 222); System.out.println (E2.get (//  2

Java Basics--some common methods for object

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.