When is the add method of a hashset equal to?

I did this test comparing HashSet and equals not called

I would like to be considered equal when farAway = false (Two point distance check function)

Full compiled code, you can check it and tells you why equals is not called in this example.

 public class TestClass{ static class Posicion { private int x; private int y; @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Posicion other = (Posicion) obj; if ( farAway(this.x, other.x, this.y, other.y,5)){ return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y; return hash; } Posicion(int x0, int y0) { x=x0; y=y0; } private boolean farAway(int x, int x0, int y, int y0, int i) { return false; } } public static void main(String[] args) { HashSet<Posicion> test=new HashSet<>(); System.out.println("result:"+test.add(new Posicion(1,1))); System.out.println("result:"+test.add(new Posicion(1,2))); } } 

EDIT

- Is there a way to get HashSet to add peers to the call?

+7
source share
4 answers

If the hash codes are different from each other, there is no need to call equals() , since it is guaranteed to return false .

This follows from the general contract for equals() and hashCode() :

If two objects are equal in accordance with the equals(Object) method, then calling the hashCode method for each of the two objects should lead to the same integer result.

Your class is currently violating this contract. You need to fix it.

+22
source

If you want to always call equals() , always return, say, 0 in hashCode() . Thus, all elements have the same hash code and are compared only with equals() .

 public int hashCode() { return 0; } 
+4
source

It seems that the HashSet is not suitable for you. It looks like you want to create your own way of comparing two positions. Instead of saying "are the two positions exactly equal?" Instead, you should look at using TreeSet with a Comparator. So you can write "IsWithinRangeComparator" and do a range check there.

+1
source

As stated above, when objects are equal, their hash code must also be the same. You can make a simple fix to calculate your hash code as shown below.

  public int hashCode() { int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y; boolean faraway=farAway(this.x, other.x, this.y, other.y,5); hash=59*hash+(faraway?1:0); //include faraway also as part of hashcode computation return hash; 

}

-one
source

All Articles