"Go" java = =, equals, hashcode differences and overrides equals and Hashcode method instances

Source: Internet
Author: User
Tags ming

Original address: http://www.cnblogs.com/luankun0214/p/4421770.html

Thanks to the sharing of friends, recorded only for learning.

1. Override the Equals method instance section code reference http://blog.csdn.net/wangloveall/article/details/7899948

The purpose of overriding the Equals method is to determine the contents of two objects (there can be a lot of content, such as comparing names and ages at the same time, and whether the same object is the same).

If you do not override Equals, then the comparison will be whether the object's reference points to the same memory address, which is overridden to compare the value of two objects for equality. In particular, the use of equals to compare eight large packaging objects
(such as int,float, etc.) and the string class (because the class has overridden the Equals and Hashcode methods) objects, the default comparison is the value, which is the reference address of the comparison when comparing other custom objects.
Package Com.lk.c;class User {private String name;    private int age;    public int getage () {return age;    public void Setage (int.) {this.age = age;      } public void SetName (String name) {this.name = name;      } public String GetName () {return name;          } public boolean equals (Object obj) {if (this = = obj) {return true;          } if (null = = obj) {return false;          } if (This.getclass () = Obj.getclass ()) {return false;          } User user = (user) obj;          if (This.name.equals (user.name) &&this.age = = User.age) {return true;      } return false;          }} public class Test6 {public static void main (string[] args) {User UserA = new User ();        Usera.setname ("Wang Ming");        Usera.setage (10);          User UserB = new user ();        Userb.setname ("Wang Ming");        Userb.setage (10);User UserC = new user ();        Userc.setname ("Wang Liang");        Userc.setage (10);          System.out.println ("UserA equals UserB:" + usera.equals (UserB));    System.out.println ("UserA equals UserC:" + usera.equals (UserC));      }  }
UserA equals Userb:trueusera equals Userc:false

In Java, What do you mean by overriding the Equals method to rewrite the Hashcode method?

The reasons are as follows: When the equals of this method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code . As follows:
(1) when Obj1.equals (OBJ2) is true, obj1.hashcode () = = Obj2.hashcode () must be true
(2) when obj1.hashcode () = = Obj2.hashcode () is False, Obj1.equals (OBJ2) must be false

Hashcode is a fast access for hashing data, such as using the Hashset/hashmap/hashtable class to store data, based on the hashcode value of the stored object to determine whether the same.

So if we rewrite the euqals for an object, it means that as long as the values of the member variables of the object are equal then Euqals equals true, but does not rewrite hashcode, then we are new to the object, When the original object. Equals (New Object) equals True, the hashcode of the two are different, resulting in an inconsistent understanding.

2, look at the following three procedures

Package Com.lk.c;public class Test7 {public static void main (string[] args) {int a = 10;        int B = 10;        System.out.print ("Basic type a==b:");        System.out.println (A = = B);                SYSTEM.OUT.PRINTLN ("-----");        String S1 = "abc";        String s2 = "abc";        System.out.print ("String type is s1==s2:");        System.out.println (S1 = = s2);                SYSTEM.OUT.PRINTLN ("-----");        String s3 = new String ("abc");        String S4 = new String ("abc");//You can see that = = compares the stack's address for the same System.out.print ("String type with new string () is s1==s2:");        System.out.println (s3 = = S4);        System.out.println (S1 = = S3);                SYSTEM.OUT.PRINTLN ("-----");        Integer i1 = 1;        Integer i2 = 1;        System.out.print ("Package type is i1==i2:");        System.out.println (I1 = = I2);                SYSTEM.OUT.PRINTLN ("-----");        Integer i3 = 128;       Integer I4 = 128;//The output is false because the integer is cached between 128-127 and the System.out.print is not cached beyond this range ("The wrapper type is i3==i4:"); System.out.println (i3 = = I4);                SYSTEM.OUT.PRINTLN ("-----");        Integer i5 = new Integer ("1");        Integer I6 = new Integer ("1");        System.out.print ("Packing type with new Integer () is i5==i6:");                SYSTEM.OUT.PRINTLN (i5 = = I6);//With new Integer () How much will not cache System.out.println ("-----");        A a1 = new A (1);        A a2 = new A (1);        A a3 = A2;        System.out.print ("ordinary reference type A1 = = A2:");        SYSTEM.OUT.PRINTLN (a1 = = A2);    SYSTEM.OUT.PRINTLN (A2 = = A3);//Objects assigned to new objects are the same System.out.println ("-----");    }}class a{int i;    Public A (int i) {this.i = i; }}
The base type a==b:true-----String type is s1==s2:true-----string type with new string () is s1==s2:falsefalse-----The wrapper type is I1==I2: True-----wrapper type is i3==i4:false-----wrapper type with new Integer () is i5==i6:false-----Generic reference type A1 = = a2:falsetrue-----
Package Com.lk.c;public class Test8 {public static void main (string[] args) {//TODO auto-generated method Stu        b System.out.println ("Basic type does not have Equals method");                SYSTEM.OUT.PRINTLN ("-----");        String S1 = "abc";        String s2 = "abc";        System.out.print ("Equals method of String type:");        System.out.println (s1.equals (S2));                SYSTEM.OUT.PRINTLN ("-----");        String s3 = new String ("abc");        String S4 = new String ("abc");//You can see that comparing the Equals method compares the values in the heap with the same System.out.print ("The Equals method of the string type new string ():");        System.out.println (S3.equals (S4));                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("string is assigned with = = and is compared with the value of the new string ():");        System.out.println (S1.equals (S3));                SYSTEM.OUT.PRINTLN ("-----");        Integer i1 = 1;        Integer i2 = 1;        System.out.print ("The Equals method of the wrapper class:");        System.out.println (I1.equals (I2));                SYSTEM.OUT.PRINTLN ("-----"); Integer i3 = new Integer (1);        Integer i4 = new Integer (1);        System.out.print (The new Integer () of the wrapper class is used with the Equals method: ");        System.out.println (I3.equals (I4));                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("Integer with = = Assignment and a comparison with the new Integer ():");        System.out.println (I1.equals (i3));    SYSTEM.OUT.PRINTLN ("-----"); }}
The base type does not have the Equals method-----The Equals method of the String type: True-----The Equals method of the string type new string (): True-----string is assigned with = = and with new string () Comparison of assignments: true-----The Equals method of the wrapper class: True-----The new Integer () of the wrapper class with the Equals method: True-----integer is assigned with = = and with the new Integer () Comparison of assignments: true-----
Package Com.lk.c;public class Test9 {public static void main (string[] args) {//TODO auto-generated method Stu        b Student S1 = new Student ("Akkun", 21);        Student s2 = new Student ("Akkun", 21);        Student s3 = new Student ();        Student S4 = new Student ();        Student S5 = S1;        System.out.print ("= = Non-default construction of ordinary class objects:");        System.out.println (S1 = = s2);        System.out.println (S1 = = S5);                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("equals non-default construct of the ordinary class object:");        System.out.println (s1.equals (S2));        System.out.println (S1.equals (S5));                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("= = default construction of the ordinary class object:");        System.out.println (s3 = = S4);                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("equals default construct of the ordinary class object:");        System.out.println (S3.equals (S4));                SYSTEM.OUT.PRINTLN ("-----");        System.out.print ("Compare attributes of ordinary objects equals:");        System.out.println (S1.name.equals (s2.name));System.out.print ("Comparing the properties of a normal object = =:");    System.out.println (S1.name = = S2.name);    }}class student{public String name;    public int age;        Public Student () {} public Student (String Name,int age) {this.name = name;    This.age = age;        } public void Test () {System.out.println (this.name);    System.out.println (This.age); }}
= = Non-default construction for ordinary class objects: falsetrue-----equals non-default construct for ordinary class objects: Falsetrue-----General Class Object = = Default construct: False-----The equals default construct of a normal class object: False-----Compare the properties of a normal object Equals:true compare the properties of a normal object ==:true

From the above three programs can be seen:

1) for = =: In a simple type (int, etc.), this method can be used to compare, this type does not have the Equals method, the value of int is present in the stack, = = compares the contents of the stack is the same. In string types, it is more special to use string= ""; When this assignment is made, the two same values are the same as the = = comparison. But with new String (), the assignment is not the same. when explaining string= "", Java checks whether the same value is in the heap, and if so, the address of the new object is also assigned the same as the address of the old object, so = = Comparison will be the same. But new String () opens up two stacks, so the = = comparison is not the same. For wrapper classes, such as integer= "", when there is a cache in-128-127, see the program above. The other case is similar to string.

2) for equals: When the string type or wrapper class, such as Integer, compares the value in the heap, and the integer has no cache. For the normal class, the first address of the memory that equals compares, this time and = = is the same, that is, comparing the two sides pointing to is not the same object. please see Cheng for details.

The above procedures have been tested in person. Hope to be helpful to everyone.

Here are some of the claims found in Baidu: Http://zhidao.baidu.com/link?url=AMYxGo3NunWY7irH5XLPlHUa0ywvyqgYEAdDUMKJlQvklm686MC_ D7zjt3dx9bmuzwxxjwrv2qhelgj8gzaxbk

In Java, (1) for a string variable, equal compares the contents of both sides of the object, so the content returned is true. As for the "= =" that you did not ask, the first address in memory is compared, so if it is not the same object, "= =" does not return true but false. For a simple example, String s1= "abc", s2= "abc"; String s3 =new String ("abc"); String S4=new string ("abc"), S1==s2//true,s1.equals (S2)//true,s3.equals (S3)//true,equal Compare content s3==s4//false,== Compare the first address, so is false(2) for non-string variables, equals the memory of the first address, this time and = = is the same, that is, the comparison between the two points is not the same object, that is, sample SA1 = new sample (); Sample SA2 = new sample (); Sa1.equals (SA2)//false, as not the same object note, if added SA1=SA2; sa1.equals (SA2)//true

"Go" java = =, equals, hashcode differences and overrides equals and Hashcode method instances

Related Article

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.