When do I need to rewrite equals ()?
Equals () returns a true value only if an instance equals itself. In layman's words, the comparison at this point is whether the two references point to the same object in memory, or whether the instances are equal. When we use Equals () to compare two references to value objects, we often want to know if they are logically equal, not whether they point to the same object. In such a case, if the superclass does not override Equals () to achieve the desired behavior, then we need to rewrite the Equals method.
Here is a simple example, we need a series of orderelement objects, but when PropertyName already have the situation, we do not need, then in fact, when we compare two objects, we only need to know whether their property value is equal to it:
1 Public classorderelement {2 3 Publicorderelement () {4 }5 6 Publicorderelement (Integer OrderNo, String PropertyName, Boolean isasc) {7 This. OrderNo =OrderNo;8 This. PropertyName =PropertyName;9 This. ISASC =Isasc;Ten } One A PrivateInteger OrderNo; - PrivateString PropertyName;//Sort Properties - PrivateBoolean ISASC;//whether the positive order the - PublicInteger Getorderno () { - returnOrderNo; - } + - Public voidSetorderno (Integer orderno) { + This. OrderNo =OrderNo; A } at - PublicString Getpropertyname () { - return This. PropertyName; - } - - Public voidSetpropertyname (String PropertyName) { in This. PropertyName =PropertyName; - } to + PublicBoolean getisasc () { - return This. Isasc; the } * $ Public voidSetasc (Boolean isasc) {Panax Notoginseng This. ISASC =Isasc; - } the + @Override A Publicboolean equals (Object obj) { the if(obj = =NULL|| ! This. GetClass (). GetName (). Equals (Obj.getclass (). GetName ())) + return false; -Orderelement e = orderelement.class. Cast (obj); $ if(Getpropertyname ()! =NULL&& e.getpropertyname ()! =NULL&&getpropertyname (). Equals (E.getpropertyname ())) $ return true; - returnsuper.equals (obj); - } the - @OverrideWuyi Public inthashcode () { the if(Getpropertyname ()! =NULL) { - returngetpropertyname (). Hashcode (); Wu } - returnSuper.hashcode (); About } $}
This application is very common, if necessary, we should be in their own class to rewrite these two methods!
Override Equals () and Hashcode ()