#Collections HashSet not using my classes `equals` method

1 messages · Page 1 of 1 (latest)

hazy zephyr
#
private static class Coord {
    public int x, y;
    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
    }
  
    @Override
    public boolean equals(Object o) {
        if (this.getClass() != o.getClass()) return false;
        Coord c = (Coord) o;
        return this.x == c.x && this.y == c.y;
    }
HashSet<Coord> set = new HashSet<>();
set.add(new Coord(1, 1));
set.add(new Coord(1, 1));
System.out.println(set.size()) // 2 is outputed

The docs say that it runs .equals on them

runic sirenBOT
#

<@&987246452180930620> please have a look, thanks.

hazy zephyr
#

I found that I also needed to override hashCode, dont know why that is not more clear in the docs

@Override
   public int hashCode() {
       return Objects.hash(suit, rank);
   }
runic sirenBOT
#

Closed the thread.

ancient onyx
#

Maybe just needs to be more prominent? Certainly I think it should be more clear in hashCode

Object.equals JavaDoc

API Note:
It is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Object.hashCode JavaDoc

If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.