1

There are two objects:

    private class Monkey{
        String name;

        public Monkey(String name) {
            this.name = name;
        }

        @Override
        public boolean equals(Object obj) {
            return name.equals(((Monkey) obj).name);
        }
    }
    @Test
    public void contain(){
       Monkey monkey1 = new Monkey("Jon");
       Monkey monkey2 = new Monkey("Jon");

        java.util.Set<Monkey> monkeySet = new HashSet<>();
       monkeySet.add(monkey1);

       System.out.println(monkeySet.contains(monkey2));
       // false

       monkeySet.add(monkey2);
       System.out.println(monkeySet.size());
       // 2
    }

With HashSet,it think monkey1 and monkey2 are not same object. But in my project, if monkey1.name == monkey2.name, then they should be same.

What can I do to make HashSet think monkey1 and monkey2 is same ?

Shuai Li
  • 2,426
  • 4
  • 24
  • 43

2 Answers2

2

You also need to override hashCode along equals to make this things identical. Here is an example how to do it:

@Override
public int hashCode() {
    return Objects.hash(name);
}

please read this good reads to know why you need to do this: why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
1

Hashset uses hashcode of class in equals methods. Currently, you're using default hashcode and equals method returns false. Use following code in your Monkey class and you'll get required result.

private class Monkey{
    String name;

    public Monkey(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
       if (this == o)
          return true;
       if (!(o instanceof Monkey))
          return false;

       Monkey monkey = (Monkey) o;

      return name.equals(monkey.name);
   }

   @Override
   public int hashCode() {
     return name.hashCode();
   }
}
Tayyab Razaq
  • 348
  • 2
  • 11