Object class learning Equals method rewrite

Source: Internet
Author: User

We know that all classes in Java have the Equals method because the object class owns the Equals method

The public boolean equals (Object obj) in object objects, indicating whether another object is "equal" to this object. The equality here means that the two sides of the comparison point to the same object
For any non-null reference value x and Y, this method returns True if and only if X and Y refer to the same object (that is, the same memory address);
But that's not what we need in life, for example, an array of objects that do not allow duplicate values, our rule holds that the same object is a duplicate object, and when we insert an object into the array, the array must first determine whether the inserted object exists, replace it if it exists, and insert it without being present. But the Equals method is obviously not judged, because the memory address of the new object is always different, so the duplicate values appear in the array. This is clearly the time to rewrite the Equals method of the array class, in which we add our own logic.
The JDK API recommends that when this method is overridden, it is often necessary to override the Hashcode method to maintain the general contract for the Hashcode method, which declares that the equality object must have an equal hash code.
The conventional agreement for the Hashcode method means:
(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
So when we rewrite the Equals method, we add our own logic. Or as an example of the above array, we rewrite the Equals method and stipulate that as long as all of the object's property values are the same, two objects are equal, obviously our purpose can be easily achieved. But we did not rewrite the Hashcode method. The memory address of the object that the Hashcode method still returns, so the hashcode value of the two objects is still not equal, which violates the general contract of the Hashcode method.
What is the consequence of violating this agreement, which can cause confusion in some cases where the object hashcode value is indexed. It's the equivalent of not rewriting the Equals method.
Example:
Class person{public String name;
	private int age;
		Public person (String Name,int age) {this.name = name;
	This.age = age; //Here I rewrite the Equals method, which stipulates that all property values for person are equal.
		Two objects are equal @Override public boolean equals (object obj) {if (obj = =) return true;
				if (obj instanceof person) {try {Boolean check = true;
				field[] Objectfields = Obj.getclass (). Getdeclaredfields ();
				field[] Personfields = Obj.getclass (). Getdeclaredfields ();
						for (int i = 0;i< objectfields.length;i++) {if (!objectfields[i].get (obj). Equals (Personfields[i].get (this)) {
						Check = false;
					Break
				
			} return check;
			catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		return true;
	return false; ///Rewrite the Hashcode method to convert the object's name and age attribute to a string, returning the hashcode value of the secondary string @Override public int hashcode () {String id = this.name + th
		Is.age + "";
	return Id.hashcode (); } public class Objectdemo {public static void main (string[] Args) throws IllegalArgumentException, illegalaccessexception {person p = new person ("Fanjie", 23);

		person P2 = new Person ("Fanjie", 23);
		System.out.println (P.equals (p2));
		
	System.out.println (p.hashcode () = = P2.hashcode ());

 }
	
	
}


What needs to be explained is that there are a number of rules to override the Equals method:
Reflexivity: Should return true for any non-null reference value x,x.equals (x). Symmetry: For any non-null reference value x and Y, x.equals (y) should return true if and only if Y.equals (x) returns True. Transitivity: For any non-null reference value x, Y, and Z, if X.equals (y) returns true and Y.equals (z) returns True, then X.equals (z) should return true. Consistency: For any non-null reference value x and Y, multiple calls to X.equals (Y) always return TRUE or always return false, provided that the information used in the Equals comparison on the object has not been modified.  False should be returned for any non-null reference value x,x.equals (null). Here is just the simplest rewrite, interested students can study it carefully.

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.