HashSet with two equals object?

人走茶凉 提交于 2019-12-18 06:55:01

问题


I created an object HashSet, and the value is an object (Triple) which is my own class. But I get a strange thing, when there are two equal objects on my HashSet, is it possible? Here is my overriding method for the equals in the class Triple

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

}


回答1:


You need to be sure to implement hashCode() as well, and when two Triples are equal, their hashCodes must also be equal. If you don't do that, you will get strange behavior.




回答2:


You didn't override equals and hashCode in your class properly. Here's how to write it and test it :

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf




回答3:


Looks like it returns true for Strings only...i tries to run the below code

            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");

the output is as below:

dont have C2 obj has k2 obj

when i change k2 to final String k2 = "Test";, the output is

dont have C2 obj dont have k2 obj




回答4:


I am having trouble understanding your question but hashCode() and equals() sematics are important only when you are planning to use an object as the key. And you cant have two objects evaluating to same hash in a Map...one will override the other



来源:https://stackoverflow.com/questions/4055780/hashset-with-two-equals-object

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