HashSet 和 TreeSet 判断集合内元素相等的方法
HashSet
public boolean equals(Obiect object) 和 public int hashCode()
缺一不可
例:
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<TestClass> testSet = new HashSet<>();
TestClass t1 = new TestClass("qwe");
TestClass t2 = new TestClass("qwe");
testSet.add(t1);
testSet.add(t2);
for (TestClass t : testSet) {
System.out.println("id: " + t.id + " hashCode: " + t.hashCode());
}
}
}
class TestClass {
String id;
TestClass(String id) {
this.id = id;
}
@Override
public int hashCode(){
return id.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof TestClass) {
TestClass t = (TestClass) o;
return this.id.equals(t.id);
} else {
return false;
}
}
}
输出:
id: qwe hashCode: 112383
若缺少hashCode(),输出:
id: qwe hashCode: 1118140819
id: qwe hashCode: 1975012498
若缺少equals(Object object),equals方法比较两个对象的地址,输出:
id: qwe hashCode: 112383
id: qwe hashCode: 112383
TreeSet
需要实现Comparable接口
例:
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Set<TestClass> testSet = new TreeSet<>();
TestClass t1 = new TestClass("qwe");
TestClass t2 = new TestClass("qwe");
testSet.add(t1);
testSet.add(t2);
for (TestClass t : testSet) {
System.out.println("id: " + t.id + " hashCode: " + t.hashCode());
}
}
}
class TestClass implements Comparable<TestClass>{
String id;
TestClass(String id) {
this.id = id;
}
@Override
public int compareTo(TestClass t) {
return this.id.compareTo(t.id);
}
}
输出:
id: qwe hashCode: 1118140819
网友评论