equals, = = and Hashcode in Java

Source: Internet
Author: User
Tags date1

I. = = 1, simple background Everything in Java is an object, in the program run, each object storage location has the following options: 1) Register: The fastest, least capacity, in Java memory is completely transparent-there is no control and can not recommend the compiler to store an object in memory ; 2) stack: In RAM, the stack pointer allows you to get the address of this area in memory, which can be allocated by controlling the addition and subtraction of the stack pointer. When you create a program, the Java system must know the exact life cycle of all items stored on the stack to control the movement of the stack pointer. Object references to basic types of objects and other objects are stored in this area. 3) Heap: Heap is a common memory pool, also in RAM, for storing most Java objects. A point where the heap differs from the stack is that the compiler does not need to know the exact life cycle of the objects in the heap. The objects generated with new are stored in the heap. 2, = = The real understanding of the storage location of objects in Java, we can say: = = The job is to compare two objects in the stack is the same content. Specifically, for basic types-including Boolean, Char, Byte, short, int, long, float, double, and void-because their defined objects are stored on the stack, using = = is the comparison value equal.
public class Test {public static void main (string[] args) {int i1=10;int i2=10;int I3=15;boolean Bool1=false;boolean bool2 =false;boolean bool3=true;char c1= ' x '; char c2= ' x '; char c3= ' y '; short s1=255;short s2=255;short s3=128;byte b1=64;byte B2 =64;byte b3=32;long l1=100;long l2=100;long l3=200;float f1=3.14f;float f2=3.14f;float f3=6.28f;double d1=2.78;double D2=2.78;double d3=5.56; System.out.print ("I1==i2?"); System.out.println (I1==I2); System.out.print ("I2==i3?"); System.out.println (I2==I3); System.out.print ("L1==l2?"); System.out.println (L1==L2); System.out.print ("L2==l3?"); System.out.println (L2==L3); System.out.print ("Bool1==bool2?"); System.out.println (bool1==bool2); System.out.print ("Bool2==bool3?"); System.out.println (BOOL2==BOOL3); System.out.print ("S1==s2?"); System.out.println (S1==S2); System.out.print ("S2==s3?"); System.out.println (S2==S3); System.out.print ("C1==c2?"); System.out.println (C1==C2); System.out.print ("C2==c3?"); System.out.println (C2==C3); System.out.print ("B1==b2?"); System.out.println (B1==B2); System.out.print ("B2==b3?"); System.out.println (B2==B3); System.out.print ("F1==f2?"); System.out.println (F1==F2); System.out.print ("F2==f3?"); System.out.println (F2==F3); System.out.print ("D1==d2?"); System.out.println (D1==D2); System.out.print ("D2==d3?"); System.out.println (D2==D3);}}
The output is as follows:
I1==i2?truei2==i3?falsel1==l2?truel2==l3?falsebool1==bool2?truebool2==bool3?falses1==s2?trues2==s3?falsec1==c2 ? truec2==c3?falseb1==b2?trueb2==b3?falsef1==f2?truef2==f3?falsed1==d2?trued2==d3?false

For most other objects, the stack stores only the object reference, not the object's content, so the = = comparison is a comparison of whether the reference is equal, that is, whether to point to the same object in the heap.
public class Test {public static void main (string[] args) {string str1 = new String ("abc"); String str2 = new String ("abc"); String STR3 = str1;date date1 = new Date ();D ate date2 = new Date ();D ate date3 = date1; Person P1=new person (); Person P2=new person (); Person P3=P1; System.out.print ("Str1==str2?"); System.out.println (STR1==STR2); System.out.print ("Str1==str3?"); System.out.println (STR1==STR3); System.out.print ("Date1==date2?"); System.out.println (DATE1==DATE2); System.out.print ("Date1==date3?"); System.out.println (Date1==date3); System.out.print ("P1==p2?"); System.out.println (P1==P2); System.out.print ("P1==p3?"); System.out.println (P1==P3);}}
The output is as follows:
Str1==str2?falsestr1==str3?truedate1==date2?falsedate1==date3?truep1==p2?falsep1==p3?true
3, the special case of the quotation string strings Java provides a way for a special instance object to string: by-quote string.
String str1 = "abc";
Note that the quote string is stored in an area called a string pool. There is a string pool in the JVM, many string objects are saved in the string pool, and can be shared. Therefore, the string pool improves efficiency. When a string object is created with a quoted string, the JVM first looks in the string pool for the corresponding object, or, if present, returns a reference to the existing object, otherwise creates a new object in the pool and returns the reference.
public class Test {public static void main (string[] args) {String str1 = "abc"; String str2 = "abc"; String Str3=new string ("abc"); System.out.print ("Str1==str2?"); System.out.println (STR1==STR2); System.out.print ("Str1==str3?"); System.out.println (STR1==STR3);}}
The output is as follows:
Str1==str2?truestr1==str3?false
Since str1 and str2 are all created by quotation marks, when STR2 is established, "ABC" already exists in the string pool, so the JVM returns this reference directly, so STR==STR2 is established, and STR3 is created by new and not saved in the string pool. That is, the STR3 content stored in the stack is not the same as the content of the Stre1, so str3==str1 is not true. The string pool can be accessed through the Intern () method of String. The Intern () method searches the string pool for an object that already exists in the string pool that is the same as the current object, returns the corresponding reference in the string pool if it exists, adds the current object to the string pool if it does not exist, and then returns the reference.
public class Test {public static void main (string[] args) {String str1 = "abc"; String str2 = "abc"; String Str3=new string ("abc"); Str3=str3.intern (); System.out.print ("Str1==str2?"); System.out.println (STR1==STR2); System.out.print ("Str1==str3?"); System.out.println (STR1==STR3);}}
This is the output as follows:
Str1==str2?truestr1==str3?true
As you can see, through Intern (), STR3 becomes the same reference to STR1 and Stre2 in the string pool. 4. For the basic type wrapper Java provides a wrapper type for each base type, and the wrapper type is more like a well-defined class. The corresponding relationship between the base type in Java and the wrapper type is the following table.
Basic type Size Wrapper type
Boolean - Boolean
Char 16bit Character
Byte 8bit Byte
Short 16bit Short
Int 32bit Integer
Long 64bit Long
Float 32bit Float
Double 64bit Double
void - Void


The wrapper type also supports the creation of objects similar to the base type, and the operation of = = for objects constructed in this manner is related to the type. For integer, Boolean, Character, Byte, Long these types, = = comparison values are equal;
public class Test {public static void main (string[] args) {Integer I1 = 10;integer i2 = 10; Boolean bool1 = false; Boolean bool2 = false; Character C1 = ' x '; Character c2 = ' x '; Short S1 = 255; Short S2 = 255; Byte B1 = 64; Byte b2 = 64; Long L1 = 100l; Long L2 = 100l; Float f1 = 3.14f; Float F2 = 3.14f;double D1 = 2.78;double D2 = 2.78; System.out.print ("I1==i2?"); System.out.println (I1 = = I2); System.out.print ("L1==l2?"); System.out.println (L1 = = L2); System.out.print ("Bool1==bool2?"); System.out.println (bool1 = = bool2); System.out.print ("C1==c2?"); SYSTEM.OUT.PRINTLN (C1 = = C2); System.out.print ("B1==b2?"); System.out.println (B1 = = b2); System.out.print ("S1==s2?"); System.out.println (S1 = = s2); System.out.print ("F1==f2?"); System.out.println (f1 = = F2); System.out.print ("D1==d2?"); System.out.println (D1 = = D2);}}
The results of the operation are as follows:
I1==i2?truel1==l2?truebool1==bool2?truec1==c2?trueb1==b2?trues1==s2?falsef1==f2?falsed1==d2?false
For short, float, and double types where values are equal, = = still gets false. For objects that are created with new, all of the wrapper types stored in the stack are references to objects, that is, the = = comparison points to the same object.
public class Test {public static void main (string[] args) {integer i1 = new Integer (ten); integer i2 = new Integer (10); Boolean bool1 = new Boolean (false); Boolean bool2 = new Boolean (false); Character C1 = new Character (' X '); Character C2 = new Character (' X '); System.out.print ("I1==i2?"); System.out.println (I1 = = I2); System.out.print ("Bool1==bool2?"); System.out.println (bool1 = = bool2); System.out.print ("C1==c2?"); SYSTEM.OUT.PRINTLN (C1 = = C2);}}
The results of the operation are as follows:
I1==i2?falsebool1==bool2?falsec1==c2?false
Second, Equals () 1, the Equals of object (OBEJCT) provides a equals (object) method in the object class with the following source code:
    public boolean equals (Object obj) {        return (this = = obj);    }
That is, it returns true if and only if obj is pointing to the same object. Many Java classes douoverride this method, and most of the override methods are the same as the content that refers to the object. For example, the Equals method of a string compares the contents of two strings by character:
public        Boolean equals (Object anobject) {if (this = = AnObject) {return true;            } if (AnObject instanceof string) {string anotherstring = (string) anobject;            int n = value.length;                if (n = = anotherString.value.length) {char v1[] = value;                Char v2[] = Anotherstring.value;                int i = 0;                    while (n--! = 0) {if (V1[i]! = V2[i]) return false;                i++;            } return true;    }} return false; }
In Java documention, it is recommended that the custom class override this method and require the Equals method to follow the following four conventions: 1) reflexivity should always return true for any non-null reference x,x.equals (x) ; 2) symmetry for any non-null reference x and Y,x.equals (y) returns true if and only if Y.equals (x) returns TRUE;3) transitivity for any non-null reference x, Y, and Z, if X.equals (y) returns True, Y.equals (z) returns True, then X.equals (z) also returns TRUE;4) invariance for any non-null reference Concord Y, if the information in X and y involving the Equals () method is not modified between multiple calls to Equals (), Then multiple invocations should return the same value. 2. Custom class overrides Equals (object) If there is no Override Equals method in the custom class, then the Equals method in object is inherited, that is, compares two references to the same object. This may not be the result you want, so you can override the custom implementation logic in the Equals method. The following code gives a rough example.
public class Person {private string id;private string name;private int age;public person (string ID, string name, int age) {super (); this.id = Id;this.name = Name;this.age = age;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic boolean equals (Object obj) {//TODO auto-generated method stubif (Obj==null) return false;if (! ( obj instanceof person) return false; Person person= (person) obj;if (this.id==null) {return  person.getid () ==null;} Return This.id.equals (Person.getid ());}}

3. Custom Equals () Note 1) Common short-circuit optimization measures for non-static Equals method, when obj==null must return false; In general, for! (obj instanceof XXX) can return false, can also be judged by This.getclass ()!=obj.getclass (), 2) non-final class avoid using Obj.getclass ()! =xxxclass.class to judge that a non-final class might have subclasses, and if the subclass does not have the override Equals method, then the Equals method of the superclass is used, and the above notation causes always return false, which should be used with This.getclass ()! =obj.getclass () judgment. Third, hashcode () Java Dodumention recommends that each class that has the Equials override should override Hashcode. It is common to use Hashtable, HashMap, and hashset errors due to the absence of the override Hashcode method. If a class does not have an override Hashcode method, it inherits the Hashcode method of object, which, according to the Convention, hashcode the same as true for equals. For object, only two references to the same object will be true for equals, and for different references it should be assumed that the Hashcode method of object will have a distinct two number. Java also has a convention on Hashcode: 1) When the application is running, if the information used by the Equals method of an object is not modified, the Hashcode method is called multiple times for that object and should always return the same integer. This integer can be different when a program executes multiple times; 2) If two objects are equal according to the Equals method, then the results of the hashcode methods of the two objects are equal, i.e. two objects with different hashcode results, equals Method must get False;3) for the Equals method to get false two objects, does not require their Hashcode method to obtain the result also must be different.
public class Test {public static void main (string[] args) {hashmap<person,string>map=new Hashmap<person, String > (); Person P1=new person ("101", "Jack", 20); Person P2=new person ("101", "Jack", 20); System.out.print ("P1.equals (p2)?"); System.out.println (P1.equals (p2)); Map.put (P1, "test"); System.out.println (Map.get (P2));}}
The above code outputs the result:
P1.equals (p2)? Truenull
Because the Equals is true object Hashcode should also be the same, and HashMap also need to get hashcode to calculate the object's storage index, so if two objects hashcode different, Hashmao is considered to be different objects. In the GET, it is also based on the object's hashcode to calculate the corresponding index, and then to see the corresponding position there are no objects. In the above example, because the person does not have the override Hashcode method, the Hashcode method of object is used, p1 and P2 hashcode get different values. The following generation has modified the definition of person:
public class Person {private string id;private string name;private int age;public person (string ID, string name, int age) {super (); this.id = Id;this.name = Name;this.age = age;} Public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic boolean equals (Object obj) {//TODO auto-generated method stubif (Obj==null) return false;if (! ( obj instanceof person) return false; Person person= (person) obj;if (this.id==null) {return  person.getid () ==null;} Return This.id.equals (Person.getid ());} @Overridepublic int hashcode () {//TODO auto-generated method stubif (id==null) return 0;return this.id.hashCode ();}}
Java has rewritten the hashcode of string to ensure that the same string content gets the same hashcode. The following is the Hashcode code in string:
    public int hashcode () {        int h = hash;        if (h = = 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = + * H + val[i];            }            hash = h;        }        return h;    }





equals, = = and Hashcode in Java

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.