HashSet允许重复

我似乎无法使HashSet实例正常工作。我使用的代码如下:

import testing.Subclass;

import java.util.HashSet;

public class tester {

public static void main(String[] args) throws Exception {

HashSet<Subclass> set = new HashSet<Subclass>();

set.add(new Subclass("007812"));

set.add(new Subclass("007813"));

System.out.println("Set size " + set.size());

set.add(new Subclass("007812"));

System.out.println("Set size " + set.size());

for(Subclass sub : set) {

System.out.println(" sub acctNbr " + sub.getAcctNbr());

}

}

}

子类

public class Subclass implements Comparable<Subclass> {

public Subclass(String acctNbr) {

this.acctNbr = acctNbr;

}

private String acctNbr;

public String getAcctNbr() {

return this.acctNbr;

}

public int compareTo(Subclass other) {

return this.getAcctNbr().compareTo(other.getAcctNbr());

}

public boolean equals(Subclass other) {

if(other.getAcctNbr().equals(this.getAcctNbr()))

return true;

else

return false;

}

public int hashCode() {

return acctNbr.hashCode();

}

}

该代码输出

sross@sross-workstation:~/Documents$ javac testing/Subclass.java

sross@sross-workstation:~/Documents$ javac tester.java

sross@sross-workstation:~/Documents$ java tester

Set size 2

Set size 3

sub acctNbr 007812

sub acctNbr 007812

sub acctNbr 007813

sross@sross-workstation:~/Documents$

回答:

您需要覆盖equals(Object)。而不是这样做,您实现了一个equals带有signature

的方法equals(Subclass)。因此,您HashSet使用的是为相等性测试equals(Object)定义的默认方法Object

默认equals(Object)实现基于对象标识,因此,该集合“允许”您添加两个String在语义上相等的不同对象。

以上是 HashSet允许重复 的全部内容, 来源链接: utcz.com/qa/401101.html

回到顶部