override equals in Java

equals() (javadoc) must define an equality relation (it must be reflexivesymmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

Steps to Override equals method in Java

Here is my approach for overriding equals method in Java. This is based on standard approach most of Java programmer follows while writing equals method in Java.
 
1) Do this check -- if yes then return true.
2) Do null check -- if yes then return false.
3) Do the instanceof check,  if instanceof return false than return false from equals in Java , after some research I found that instead of instanceof we can use getClass() method for type identification because instanceof check returns true for subclass also, so its not strictly equals comparison until required by business logic. Butinstanceof check is fine if your class is immutable and no one is going to sub class it. For example we can replace instanceof check by below code
 
if((obj == null) || (obj.getClass() != this.getClass()))
        return false;
 
4) Type cast the object; note the sequence instanceof check must be prior to casting object.
 
5) Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks.  If first field does not match, don't try to match rest of attribute and return false. It’s also worth to remember doing null check on individual attribute before calling equals() method on them recursively to avoid NullPointerException during equals check in Java.

In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Langlibrary. An example:

 public class Person {
private String name;
private int age;
// ... public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
} public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Person))
return false; Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}

OR

 /**
* Person class with equals and hashcode implementation in Java
* @author Javin Paul
*/
public class Person {
private int id;
private String firstName;
private String lastName; public int getId() { return id; }
public void setId(int id) { this.id = id;} public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
} Person guest = (Person) obj;
return id == guest.id
&& (firstName == guest.firstName
|| (firstName != null && firstName.equals(guest.getFirstName())))
&& (lastName == guest.lastName
|| (lastName != null && lastName .equals(guest.getLastName())));
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
} }

Also remember:

When using a hash-based Collection or Map such as HashSetLinkedHashSetHashMapHashtable, orWeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

上一篇:pickle模块的基本使用


下一篇:使用HTML5 API(AudioContext)实现可视化频谱效果