1

this is my Student Class, I want to differentiate Student Object on the basis of Name field. But When main class executed i am getting wrong output.

public class Student {

int id;
String name;

public Student(String name, int id)
{
    this.name=name;
    this.id= id;
}


public int hashCode()
{
    return this.id;
}

public String toString()
{
    return "Student: "+this.name+"@"+Integer.toHexString(hashCode());
}



public boolean equals(Object o)
{
    if(o instanceof Student)
    {
    String name=this.name;
    Student s=(Student)o;

    if(s.name.equals(name))
    return true;
    else 
    return false;
    }
    else
    return false;

}}

//this is my main class

public class HashSett {

public static void main (String[] args)
{

    HashSet<Student> h=new HashSet<>();

    h.add(new Student("Nimit",1));
    h.add(new Student("Rahul",3));
    h.add(new Student("Nimit",2));

    System.out.println(h); 
 }
}

//this is wrong output i got

[Student: Nimit@1, Student: Nimit@2, Student: Rahul@3]

why two times "Nimit" objects are added???

2 Answers2

3

Your hashCode doesn't match your equals implementation. If a.equals(b) is true, a.hashCode == b.hashCode() must also be true.

Since equals only requires that the names are equal, hashCode should return name.hashCode().

public int hashCode()
{
    return name.hashCode();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Generate toString, hashCode and equals from Eclipse generate option or similar option from any IDE