We can have two objects which are equal but have different hash code.
But you want to store it as key in Map interface then hashcode and equals both must be equal for the equal object.
import java.util.HashMap;
import java.util.Map;
/**
* @author Arun
*/
public class EqualObjectsWithDifferentHashCode {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public static void main(String args[]) {
final EqualObjectsWithDifferentHashCode one = new EqualObjectsWithDifferentHashCode();
one.setAge(1);
one.setName("A");
final EqualObjectsWithDifferentHashCode two = new EqualObjectsWithDifferentHashCode();
two.setAge(2);
two.setName("B");
final EqualObjectsWithDifferentHashCode three = new EqualObjectsWithDifferentHashCode();
three.setAge(1);
three.setName("A");
final Map
ss.put(one, "ABC");
ss.put(two, "XYZ");
ss.put(three, "KLM");
// print hashcode of objects. Both object will have different hashcode.
System.out.println("hashcode of One=" + one.hashCode());
System.out.println("hashcode of Three=" + three.hashCode());
// check equality of the objects
System.out.println("Both objects are equal=" + one.equals(three));
// now try to fetch object from the Map
System.out.println(ss.get(three));
}
@Override
public int hashCode() {
// It is just for example. Do not follow it. It will always return different hashcode.
return (int) Math.abs((Math.random() * 1000));
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EqualObjectsWithDifferentHashCode other = (EqualObjectsWithDifferentHashCode) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
No comments:
Post a Comment