Java 具有两个相等对象的哈希集?

Java 具有两个相等对象的哈希集?,java,hashset,Java,Hashset,我创建了一个对象哈希集,值是一个对象(三元组),它是我自己的类。但我得到一件奇怪的事情,当我的HashSet上有两个相等的对象时,有可能吗?下面是我对类Triple中的equals的重写方法 @Override public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass

我创建了一个对象哈希集,值是一个对象(三元组),它是我自己的类。但我得到一件奇怪的事情,当我的HashSet上有两个相等的对象时,有可能吗?下面是我对类Triple中的equals的重写方法

 @Override
 public boolean equals(Object other){
 if (other == null) return false;
 if (other == this) return true;
 if (this.getClass() != other.getClass()) return false;
 Triple otherTriple = (Triple)other;

 if(otherTriple.getSubject().equals(getSubject()) &&
   otherTriple.getPredicate().equals(getPredicate()) &&
   otherTriple.getObject().equals(getObject()))
  return true;
 return false;

}

我很难理解您的问题,但是hashCode()和equals()语义只有在您计划使用对象作为键时才很重要。你不能让两个对象在一个映射中计算为同一个哈希值…一个将覆盖另一个

你没有正确覆盖类中的equals和hashCode。下面是如何编写和测试它:


您还需要确保实现hashCode(),当两个三元组相等时,它们的hashCode也必须相等。如果不这样做,您将得到奇怪的行为。

看起来它仅对字符串返回true…我尝试运行以下代码

            final HashSet<Car> carHashSet = new HashSet<Car>();
    final Car c1 = new  Car("black","ZX","deisel");
    final Car c2 = new  Car("black","ZX","deisel");
    carHashSet.add(c1);

    if (carHashSet.contains(c2))
        System.out.println("has c2 obj");
    else
        System.out.println("dont have C2 obj");

    final HashSet<String> stringHashSet = new HashSet<String>();

    final String k1 = "test";
    final String k2 = "test";//final String k2 = "Test";

    stringHashSet.add(k1);

    if (stringHashSet.contains(k2))
        System.out.println("has k2 obj");
    else
        System.out.println("dont have k2 obj");
final HashSet carHashSet=new HashSet();
最终车辆c1=新车(“黑色”、“ZX”、“deisel”);
最终车辆c2=新车(“黑色”、“ZX”、“deisel”);
carHashSet.add(c1);
if(carHashSet.contains(c2))
System.out.println(“具有c2对象”);
其他的
System.out.println(“没有C2对象”);
final HashSet stringHashSet=新HashSet();
最终字符串k1=“测试”;
最终字符串k2=“测试”//最终字符串k2=“测试”;
stringHashSet.add(k1);
if(stringHashSet.contains(k2))
System.out.println(“具有k2对象”);
其他的
System.out.println(“没有k2对象”);
输出如下:

没有C2 obj 有k2 obj吗

当我将k2更改为最终字符串k2=“Test”;,输出是

没有C2 obj
不要使用k2 obj

我强烈建议使用编辑器提供的Equals和HashCode builder功能,如Eclipse。两个键,keyA和keyB,可以具有相同的哈希值,而不会相互“重写”,否则哈希表的整个概念将无法工作。只有当
keyA.equals(keyB)
时,添加的最后一个将覆盖上一个。@user491748:没有区别。对象比较始终返回false,除非覆盖了if equals方法。这里的字符串比较相等方法显然返回true。要生成的哈希代码。