Equals, =, and hashcode in java

Source: Internet
Author: User

Equals, =, and hashcode in java
I. = explanation 1. simple background everything in Java is an object. When running a program, the storage location of each object has the following options: 1) Register: the fastest speed, the smallest capacity, in Java, the memory is completely transparent-it cannot be controlled or recommended that the compiler store an object into the memory; 2) STACK: in RAM, the stack pointer can be used to obtain the address of this region in the memory, and the storage can be allocated by adding or subtracting the stack pointer. When creating a program, the Java System must know the exact lifecycle of all projects stored in the stack to control the movement of the stack pointer. Objects of the basic type and object references of other objects are stored in this area. 3) Heap: a heap is a common memory pool in RAM, which is used to store most Java objects. Unlike stack, the compiler does not need to know the exact lifecycle of objects in the stack. Objects generated with new are stored in the heap. 2. = after learning about the storage location of objects in Java, we can say: = is used to compare whether the content in the stack corresponding to the two objects is the same. Specifically, for basic types, including boolean, char, byte, short, int, long, float, double, and void, because the objects they define are stored in the stack, therefore, = is used to determine whether the comparison value is 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 only stores object references rather than object content. Therefore, the = method is used to compare 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();Date date2 = new Date();Date 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. Special Cases of String quotation marks Java provides a special method of instance object for String: Use the -- quotation mark String.
String str1 = "abc";
Note that the quotation mark string is stored in a region called the string pool. The JVM contains a String pool. Many String objects are saved in the String pool and can be shared. Therefore, the string pool improves the efficiency. When a String object is created using a quote String, JVM will first look for the corresponding object in the String pool; If yes, a reference pointing to the existing object is returned; otherwise, a new object is created in the pool and the reference is returned.
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
Because both str1 and str2 are created by using quotation marks, when str2 is created, the string pool already has "abc". Therefore, the JVM directly returns this reference, so str = str2 is true; str3 is created by new and is not saved in the string pool, that is, the str3 content saved in the stack is different from the stre1 content, so str3 = str1 is not valid. You can access the String pool through the String intern () method. The intern () method searches in the string pool to check whether the same object as the current object already exists in the string pool. If yes, the corresponding reference in the string pool is returned. If no, then, the current object is added to the string pool and a reference is returned.
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);}}
The output is 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. Java provides a package type for each basic type. The package type is more like a well-defined class. The relationship between the basic types and the wrapper types in Java is shown in the following table.
Basic Type Size Package 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 object creation similar to the basic type. For objects created in this way, the = operation is related to the type. For Integer, Boolean, Character, Byte, and Long types, the = comparison value is 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 running result is as follows:
i1==i2?truel1==l2?truebool1==bool2?truec1==c2?trueb1==b2?trues1==s2?falsef1==f2?falsed1==d2?false
For the Short, Float, and Double types, if the values are equal, = still returns false. For objects created using new, all the above package Types stored in the stack are object references, that is, = compares whether to point to the same object.
public class test {public static void main(String[] args) {Integer i1 = new Integer(10);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 running result is as follows:
i1==i2?falsebool1==bool2?falsec1==c2?false
Ii. equals () Explanation 1. The Object equals (Obejct) provides an equals (Object) method in the Object class. The source code is as follows:
    public boolean equals(Object obj) {        return (this == obj);    }
That is, true is returned only when obj and this point to the same object. Many Java classes use the douoverride method. Most methods after the override method compare whether the content pointing to the object is the same. For example, The equals method of String compares the content of two strings one by one:
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;    }
We recommend that you use the override method in Java's encryption ention, and require the equals method to follow the following four Conventions: 1) Self-inverse for any non-null references x, x. equals (x) should always return true; 2) symmetry for any non-null references x and y, x. equals (y) returns true if and only if y. equals (x) returns true; 3) for any non-null references x, y, and z, if x. equals (y) returns true, y. equals (z) returns true, then x. equals (z) also returns true; 4) immutability for any non-null reference and y. If equals () is called multiple times, equals () is involved in x and y () the method information is not modified, so the same value should be returned for multiple calls. 2. The custom class overwrites equals (Object). If the override equals method is not used in the Custom class, the equals method in the Object will be inherited, that is, to compare whether two references point to the same object. This may not be the result you want, so you can customize the implementation logic in the override equals method. The following code provides 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 age) {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 () considerations 1) common short-circuit optimization measures for non-static equals methods, false will be returned when obj = null; in general,! (Obj instanceof XXX) can return false or this. getClass ()! = Obj. getClass () Judgment; 2) non-final class avoid using obj. getClass ()! = XXXClass. class to determine whether a non-final class may have sub-classes. If the sub-class does not have the override equals method, the super-class equals method will be used. The above write method will always return false. this should be used. getClass ()! = Obj. getClass. Iii. hashcode () Java dodumention It is recommended that each override equials class should override hashCode. It is common to use HashTable, HashMap, and HashSet errors because there is no override hashCode method. If a class does not have the override hashCode method, It inherits the hashCode method of the Object. According to the Conventions, the hashCode of the Object whose equals is true is the same, for an Object, only two equals references to the same Object can get true. For different references, we should think that the hashCode method of the Object will get two different numbers. Java also has a hashCode Convention: 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 for this object multiple times, always return the same integer. In the process of executing a program multiple times, this integer can be different; 2) if the two objects are equal according to the equals method, the results of the hashCode method of the two objects are also equal; that is to say, for two objects with different hashCode results, the equals method must get false; 3) for the two objects whose equals method gets false, the results obtained by their hashCode method are not required to be different.
public class test {public static void main(String[] args) {HashMap
 
  map=new HashMap
  
   ();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 output result of the above Code is:
p1.equals(p2)?truenull
Because the hashCode of the true object for equals should be the same, and HashMap also needs to obtain hashCode to calculate the storage index of the object, hashMao considers the two objects as different hashCode. In get, the corresponding index is obtained based on the hashCode of the object, and then the corresponding location is checked for the object. In the above example, because the Person does not have the override hashCode method, the hashCode method of the Object is used. The hashCode of p1 and p2 gets different values. The following buy-on-demand statement modifies the Person definition:
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 age) {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 String hashCode to ensure that the same hashCode is obtained for the same String content. The hashCode in String is as follows:
    public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }            hash = h;        }        return h;    }





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.