Reputation: 2180
My Employee Class :-
class Employee {
String name;
int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Employee))
return false;
Employee employee = (Employee) obj;
return employee.getAge() == this.getAge()
&& employee.getName() == this.getName();
}
// commented
@Override
public int hashCode() {
return (int) Math.random();
}
}
Utilization :-
Employee employee = new Employee("rajeev", 24);
Employee employee1 = new Employee("rajeev", 25);
Employee employee2 = new Employee("rajeev", 24);
HashSet<Employee> employeesList = new HashSet<Employee>();
employeesList.add(employee );
System.out.println(employeesList.contains(employee2));
System.out.println("employee.hashCode(): " + employee.hashCode()
+ " employee2.hashCode():" + employee2.hashCode());
I will get the True. But i should get the false? Because employee and employee2 are in differenct buckets and having different HashCode. Sample Output:-
true employee.hashCode(): 0 employee2.hashCode():0
What is the wrong with the code ?
All i want is different hashcode
(different bucket) and correct implementation of equals
method which returns employeesList.contains(employee2)
false.
Upvotes: 1
Views: 65
Reputation: 31269
For what you want, you can just remove the hashCode()
method from your Employee
class. The default implementation will return different values for different objects (but it only looks at object identity, so even two objects with the same values in their fields will have different hashCode
s if you don't override the method)
Note: it's not 100% guaranteed that they're different - actually it's not defined how exactly the identity hash code is created - but they will be different in practice.
The reason that your current code fails is that Math.random()
returns a value from 0 up to 1 (but never 1). If you cast that to (int)
, the result is always zero.
Upvotes: 3