Consider the below code
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1= new Person();
//Person p2= new Person();
p1.setName("same1");
//p2.setName("same2");
Person p2=p1;
Set<Person> set= new HashSet<Person>();
set.add(p1);
set.add(p2);
for(Person p: set){
System.out.println(set.size()+">>"+p.getName()+" hashcode "+p.hashCode());
}
}
}
class Person{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj){
return true;
}
@Override
public int hashCode() {
Random ran = new Random();
int x = ran.nextInt(6) + 5;
System.out.println("in hahcode method"+x);
return x;
}
}
As set does not contain duplicate, Here I have return true from equals method and return different hashcode for the same object. HashSet treat them as unique object. So far so good, as HashSet internally use HashMap to store objects.
It appears from above code snippet that HashSet use hashCode to check uniqueness not equals method. If hashCode is different for two objects,they will be stored in HashSet whether they are equal or not? Please let me know if I am missing something.