java - 如何使 java HashSet/HashMap 与任何对象一起工作?

标签 java object hashmap hashset

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

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

}

关于java - 如何使 java HashSet/HashMap 与任何对象一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214732/

相关文章:

jQuery 创建对象文字循环

java - 在 Java 中初始化 HashMap 的良好设计模式选择

java - 转换 HashMap

java - HashMap 中可以存储的键(对象)数量的理论限制?

Java: "[B@1ef9157"背后的语法和含义?二进制/地址?

java - 未收到从通知服务器发送的 GCM 通知

java - @layout/toolbar 标记中未显示后退箭头

java - 如何正确处理 Java/JDBC 中的 InnoDB 死锁?

javascript - 在 javascript 上创建一个带有 4 个按钮的对象

javascript - 在 JavaScript 中转换和组合数组