Issue with “contains” hashset method (Java)

社会主义新天地 提交于 2019-12-02 07:21:53

Without your own hashCode() implementation, Java considers two Pair objects equal only if they are the exact same object and new, by definition, always creates a 'new' object. In your case, you want Pair objects to be consider equal if they have the same values for source and target -- to do this, you need to tell Java how it should test Pair objects for equality. (and to make hash maps work the way you expect, you also need to generate a hash code that is consistent with equals -- loosely speaking, that means equal objects must generate the same hashCode, and unequal objects should generate different hash codes.

Most IDEs will generate decent hashcode() and equals() methods for you. Mine generated this:

  @Override
   public int hashCode() {
      int hash = 3;
      hash = 47 * hash + this.source;
      hash = 47 * hash + this.target;
      return hash;
   }

   @Override
   public boolean equals(Object obj) {
      if (obj == null) {
         return false;
      }
      if (getClass() != obj.getClass()) {
         return false;
      }
      final Pair other = (Pair) obj;
      if (this.source != other.source) {
         return false;
      }
      if (this.target != other.target) {
         return false;
      }
      return true;
   }

You need to override your hashCode and equals methods in your Pair class. LinkedHashSet (and other Java objects that use hash codes) will use them to locate and find your Pair objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!