Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: HashCode Behavior in HashSet

Hasnain Ali Bohra:

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 employeesList = new HashSet();
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.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: HashCode Behavior in HashSet

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×