0

I have my own class:

public class Coord {
    int x;
    int y;
    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public int hashCode() {
        int hash = (x + "-" + y).hashCode();
        return hash;
    }
}

With this Class I am testing the Hashset like this:

Set<Coord> set= new HashSet<Coord>();
set.add(new Coord(1,1));
set.add(new Coord(1,1));
set.add(new Coord(1,1));

When running this, I get a size of 3 of the hashset. I expected to have only 1. Can someone help me why ? I checked that the returned hashcode is always the same, but still the object is added to the set.

mcfly soft
  • 11,289
  • 26
  • 98
  • 202
  • 2
    Besides the `hashCode()` method, you also need to implement the `equals()` method in class `Coord` in such a way that it's in accordance to what `hashCode()` does. – Jesper Dec 14 '18 at 10:26
  • 1
    Have you tried override `equals()` at the same time? – flyingfox Dec 14 '18 at 10:26
  • All clear. Yes of course then equals. Thanks. – mcfly soft Dec 14 '18 at 10:27
  • From the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashSet.html#add(E)): *"adds the specified element `e` to this set if this set contains no element `e2` such that `Objects.equals(e, e2)`"* – Federico klez Culloca Dec 14 '18 at 10:27
  • Your IDE should have an option to generate both hashCode and equals together so you don't forget. – Peter Lawrey Dec 14 '18 at 10:33
  • Hi Peter. Do you mean for example in IntelliJ I have activly to select override methods ? Or is there any else magic option that I don't know ? – mcfly soft Dec 14 '18 at 10:44
  • @mcflysoft To generate your hashCode and Equals use the **Code | Generate** option [steps on the link](https://www.jetbrains.com/help/idea/2017.3/generating-equals-and-hashcode.html) And do not forget to, always, override both - equals and hashCode as [this note on the doc](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)) – Jonatas Emidio Dec 14 '18 at 11:38

0 Answers0