Reputation: 95
//why output of this code is 5 instead of 3 //why output of this code is 5 instead of 3 //why output of this code is 5 instead of 3//why output of this code is 5 instead of 3
public class Dummy {
public static void main(String[] args) {
Set set = new HashSet();
set.add(new Student("abc"));
set.add(new Student("abcd"));
set.add(new Student("abc"));
set.add(new Student("abc"));
set.add(new Student("abcdef"));
System.out.println(set.size());
}
}
class Student
{
private String age;
public Student(String age)
{
this.age=age;
}
public boolean equals(Student stu)
{
System.out.println("equals from Student parameter called");
return false;
}
public boolean equals(Object obj)
{
System.out.println("equals from Object parameter called");
return true;
}
public int hashcode()
{
System.out.println("hashcode called");
return 17;
}
}
Upvotes: 0
Views: 80
Reputation: 73568
It's not supposed to be public int hashcode()
, it's public int hashCode()
, so you've only overridden equals()
. There may still be "equal" (based on your implementation) objects in different buckets since they don't all get same hash.
The @Override
annotation is very helpful in these kinds of cases.
Upvotes: 3