Here is my first Class
public class MainClass {
public static void main(String args[])
{
java.util.Set s=new java.util.HashSet();
s.add(new Integer(10));
s.add(new Integer(1));
s.add(new Integer(5));
s.add(new Integer(3));
s.add(new Integer(6));
s.add(new Integer(9));
s.add(new User("John",25));
s.add(new User("John",25));
java.util.Iterator it=s.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Here is my second class
public class User {
String name;
int age;
public User(String name,int age)
{
System.out.println("I am in constructor");
this.name=name;
this.age=age;
}
@Override
public boolean equals(Object obj)
{
System.out.println("I am in equals");
User u=(User)obj;
if(this.age==u.age)
{
return this.name.equals(u.name);
}
else
{
return false;
}
}
@Override
public int hashCode()
{
System.out.println("I am in hash code");
return this.name.hashCode()+this.age;
}
@Override
public String toString()
{
System.out.println("I am in to String");
return String.format("Name: %s", this.name);
}
}
The output is
I am in constructor
I am in hash code
I am in constructor
I am in hash code
I am in equals
1
I am in to String
Name: John
3
5
6
9
10
My question is how are these elements being compared?