I did this test in a HashSet comparision and equals is not being called
I would like to consider equals when farAway=false (A function to check two point distances)
Full compilable code, you could test it, and tells why equals is not being 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 force HashSet add to call equals?
farAwayinvocation insideequals?? your class si breaking the contract betweenhashCodeandequals!hashCodeandequals. That means that when yourequalsmethod returns true then youhashCodemust return the same integer value. And that's not happening in your code.hashCode()'s contract, but also theequals()contract.equals()has to be transitive. So if you returntruefor A and B because they are close to each other and B and C because they are close to each other, you will run into problems when checking for equality between A and C if they happen to not be close. I think you'll need to devise a container/data structure other than the standard HashSet to do what you want to do (if what you want to do is even a good idea in the first place).