我似乎无法让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$