so i have a question on hashcode() and equals() method
Let's say I just write a very basic program overridng both the methodes
import java.util.*;
class Employee
{
private String name;
private int empid;
public Employee(String name,int empid)
{
this.name=name;
this.empid=empid;
}
public int getEmpid()
{
return empid;
}
public String getName()
{
return name;
}
public boolean equals(Object obj)
{
System.out.println("equals has just been called...");
Employee e1=(Employee)obj;
return ((name.equals(e1.name)) && (empid==e1.empid));
}
public int hashCode()
{
System.out.println("hashcode called...");
return empid;
}
}
Then, let's say I write another class to add and iterate the elements in HashSet
class Five
{
public static void main(String args[])
{
HashSet hs1=new HashSet();
hs1.add(new Employee("Alex",25));
hs1.add(new Employee("Peter",25));
hs1.add(new Employee("Martin",25));
hs1.add(new Employee("Alex",25));
Iterator itr=hs1.iterator();
while(itr.hasNext())
{
Employee e=(Employee)itr.next();
System.out.println(e.getEmpid()+"\t"+e.getName());
}
}
}
now the question is when i try to add Alex again with the same empid the equals() always called thee times
as there is no index n hashmap so in case if it first be checked with previously added Alex it will return true and should not be called for the other two elements (peter and martin) but equals always called 3 times
why..??
is objects within same bucket do also have the index..??