Creating a hashCode() Method - Java

后端 未结 4 1112
暗喜
暗喜 2020-12-08 21:12

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

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 22:11

    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:

    • you need to fix your compareTo method to be consistent with it.
    • you need to create a 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;

提交回复
热议问题