I\'m having some trouble writing a hashCode() method for a class I created. This class is meant to be used inside a TreeSet, and as such, it implements Comparab
Your compareTo method is not consistent with your equals method: your compareTo method says that two instances are equivalent if they have the same cost — such that a TreeSet can only ever contain at most one instance with a given cost — but your equals method says that they're only equivalent if they have the same cost and are the same in various other ways.
So, assuming that your equals method is correct:
compareTo method to be consistent with it.hashCode method that is consistent with it. I recommend using the same sort of logic as is used by java.util.List.hashCode(), which is a straightforward and effective way to assemble the hash-codes of component objects in a specific order; basically you would write something like: int hashCode = 1; hashCode = 31 * hashCode + (father == null ? 0 : father.hashCode()); hashCode = 31 * hashCode + depth; hashCode = 31 * hashCode + cost; hashCode = 31 * hashCode + matrix.hashCode(); hashCode = 31 * hashCode + java.util.Arrays.hashCode(coordinates); return hashCode;