Issue with “contains” hashset method (Java)

…衆ロ難τιáo~ 提交于 2019-12-02 13:32:02

问题


The following code is not giving me the result I'm expecting:

public static void main (String[] args) {

    Set<Pair> objPair = new LinkedHashSet<Pair>();
    objPair.add(new Pair(1, 0));

    System.out.println("Does the pair (1, 0) exists already? "+objPair.contains(new Pair(1, 0)));

}

private static class Pair {

    private int source;
    private int target;

    public Pair(int source, int target) {
      this.source = source;
      this.target = target;
    }        
}

The result will be:

Does the pair (1, 0) exists already? false

I can't understand why it's not working. Or maybe I'm using the "contains" method wrong (or for the wrong reasons).

There is also another issue, if I add the same value twice, it will be accepted, even being a set

objPair.add(new Pair(1, 0));
objPair.add(new Pair(1, 0));

It won't accept/recognize the class Pair I've created?

Thanks in Advance.


回答1:


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;
   }



回答2:


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.



来源:https://stackoverflow.com/questions/21103000/issue-with-contains-hashset-method-java

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