有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实现与集合相等

我有这门课:

private static class ClassA{
int id;
String name;

public ClassA(int id, String name){
    this.id= id;
    this.name = name;
}

@Override
public boolean equals(Object o) {
    return ((ClassA)o).name.equals(this.name);
}   

}

如果我覆盖ClassA中的方法equals,只比较名称,为什么这个main会打印2个元素

public static void main(String[] args){
    ClassA myObject = new ClassA(1, "testing 1 2 3");
    ClassA myObject2 = new ClassA(2, "testing 1 2 3");    

    Set<ClassA> set = new HashSet<ClassA>();
    set.add(myObject);
    set.add(myObject2);   
    System.out.println(set.size()); //will print 2, but I want to be 1!
}

如果我查看集合Javadocumentation

不包含重复元素的集合。更正式地说,集合不包含一对元素e1和e2,因此e1。等于(e2),最多一个空元素。正如它的名字所暗示的,这个接口为数学集合抽象建模

显然我只需要重写equals,但是我听说我还需要重写hashcode,但是为什么呢


共 (1) 个答案

  1. # 1 楼答案

    因为你也没有覆盖hashCode()

    programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode().

    http://download.oracle.com/javase/6/docs/api/java/util/Collection.html

    以及:

    The general contract of hashCode is:

    • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

    • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

    • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

    http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode()