Overriding equals() and hashCode() methods in java
equals() and hashCode() are two methods of java.lang.Object. The main use of equals() method is to compare the two objects. If the value and the two reference variables are pointing to the same memory location it returns true.
Normally the equals of method is used in HashMap. Also used in HashSet to avoid duplicates.
1) Reflexive : Object must be equal to itself.
2) Symmetric : if z.equals(x) is true then x.equals(z) must be true.
3) Transitive : if z.equals(x) is true and z.equals(y) is true then y.equals(x) must be true.
4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.
5) Null comparison : comparing any object to null must be false and should not result in NullPointerException.
hashCode() and equals();-
- If two objects are equal then their hashcode are equal.
- If two objects are not equal then their hashcode is also different.
Code Example:-
/**
*
*/
package in.jobberindia;
/**
* @author user
*
*/
public class EqualsOverRide {
private int id;
private String fName;
private String lName;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the fName
*/
public String getfName() {
return fName;
}
/**
* @param fName the fName to set
*/
public void setfName(String fName) {
this.fName = fName;
}
/**
* @return the lName
*/
public String getlName() {
return lName;
}
/**
* @param lName the lName to set
*/
public void setlName(String lName) {
this.lName = lName;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fName == null) ? 0 : fName.hashCode());
result = prime * result + id;
result = prime * result + ((lName == null) ? 0 : lName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof EqualsOverRide)) {
return false;
}
EqualsOverRide other = (EqualsOverRide) obj;
if (fName == null) {
if (other.fName != null) {
return false;
}
} else if (!fName.equals(other.fName)) {
return false;
}
if (id != other.id) {
return false;
}
if (lName == null) {
if (other.lName != null) {
return false;
}
} else if (!lName.equals(other.lName)) {
return false;
}
return true;
}
}
No comments:
Post a Comment