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???