-1

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?

Frank Serkland
  • 273
  • 4
  • 13

2 Answers2

1

Default implementation of equals() method would compare two objects memory addresses and default implementation of hashCode() method would will be object's memory address. As we're creating 2 objects pointing to different memory locations, they will be different by default, unless we define the equality and hash code by overriding the 2 methods for the class. But if you try to add the same instance twice, there will only be one instance added to the set. Hope this is clear.

Juseeth
  • 467
  • 1
  • 6
  • 18
0

Thanks to Slaw for the answer -- User doesn't override equals and hashCode.

Frank Serkland
  • 273
  • 4
  • 13
  • It is also a good practice to override compareTo by implementing Comparable interface as Treeset doesn't use the equals method. – javapedia.net Apr 02 '19 at 00:53
  • @javapedia.net You should only implement `Comparable` if the object has a _natural_ order (which `User` might). Besides, you could always use a custom `Comparator` with `TreeSet`. (Note: OP's example uses a `HashSet`). – Slaw Apr 02 '19 at 01:00