I was shown this code during a recent interview.
class User {
private Long id;
private String name;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
Set<User> set = new HashSet<>();
User user = new User();
user.setId(1L);
user.setName("test");
set.add(user);
User user2 = new User();
user2.setId(1L);
user2.setName("test");
set.add(user2);
System.out.println(set.size());
The interviewer asked me what would be printed out for the size of the set. I answered 1, since both instances of User have identical values. But after the interview I ran the code, and I got 2. Since sets are supposed to have unique values, can someone explain what's going on?