【问题标题】:How to make the java HashSet / HashMap work with any Object?如何使 java HashSet / HashMap 与任何对象一起工作?
【发布时间】:2011-08-27 13:04:56
【问题描述】:

是否可以使 HashSet 与任何 Object 一起使用?我试图使对象实现 可比,但没有帮助

import java.util.HashSet;
public class TestHashSet {
    public static void main(String[] args) {
        class Triple {
            int a, b, c;

            Triple(int aa, int bb, int cc) {
                a = aa;
                b = bb;
                c = cc;
            }
        }
        HashSet<Triple> H = new HashSet<Triple>();
        H.add(new Triple(1, 2, 3));
        System.out.println(H.contains(new Triple(1, 2, 3)));//Output is false
    }
}

【问题讨论】:

  • 如果你希望集合是可排序的——那就是当你让它具有可比性的时候。否则,equals/hashcode 实现(如答案中所述)是正确的。 Joshua Bloch 的 Effective Java 对此有很好的章节。

标签: java object hashmap hashset


【解决方案1】:

你需要实现equals(Object)hashCode()

确保当对象相等时哈希码相等

在你的例子中:

class Triple {
    int a, b, c;

    Triple(int aa, int bb, int cc) {
        a = aa;
        b = bb;
        c = cc;
    }

    public boolean equals(Object arg){
        if(this==arg)return true;
        if(arg==null)return false;
        if(arg instanceof Triple){
            Triple other = (Triple)arg;
            return this.a==other.a && this.b==other.b && this.c==other.c;
        }
        return false;
    }

    public int hashCode(){
      int res=5;
      res = res*17 + a;
      res = res*17 + b;
      res = res*17 + c;
      //any other combination is valid as long as it includes only constants, a, b and c

      return res;
    }

}

【讨论】:

    【解决方案2】:

    要使其正常工作,您需要实现 equals() 和 hashcode() 并且您还需要确保按照 Javadoc 中规定的合同正确实现它们(完全可以实现他们没有遵守这个合同,但你会得到奇怪的结果,可能很难找到错误!)

    有关说明,请参阅 here

    【讨论】:

      【解决方案3】:

      它已经适用于任何对象。我建议您需要阅读 Javadoc 而不是猜测要求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 2010-11-21
        • 1970-01-01
        • 2018-06-02
        相关资源
        最近更新 更多