我使用Set的两个实现:HashSet和TreeSet.我添加了10个元素来设置并通过set中的contains方法查找对象.我看到包含方法迭代所有对象虽然它找到了元素.出于性能原因我很困惑.为什么它是所以,我该如何预防呢?
我有一个Person类:
public class Person implements Comparable<Person>{
private int id;
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
//getter and setters
@Override
public int hashCode() {
System.out.println("hashcode:" + toString());
return this.id;
}
@Override
public boolean equals(Object obj) {
System.out.println("equals:" + toString());
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
return true;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", name=" + name + '}';
}
@Override
public int compareTo(Person o) {
System.out.println("compare to:"+getId()+" "+o.getId());
if(o.getId() == getId()){
return 0;
}else if(o.getId()>getId()){
return -1;
}else {
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
}
在主类中我添加10个Person对象,然后通过set的第一个元素调用contains方法:
import beans.Person;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Person> people = new HashSet<>();
for (int i = 0; i < 10; i++) {
people.add(new Person(i, String.valueOf(i)));
}
Person find = people.iterator().next();
if (people.contains(find)) {
System.out.println("here"+find.getName());
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
hashcode:Person{id=0, name=0} <--here element has been found but it continues
hashcode:Person{id=1, name=1}
hashcode:Person{id=2, name=2}
hashcode:Person{id=3, name=3}
hashcode:Person{id=4, name=4}
hashcode:Person{id=5, name=5}
hashcode:Person{id=6, name=6}
hashcode:Person{id=7, name=7}
hashcode:Person{id=8, name=8}
hashcode:Person{id=9, name=9}
hashcode:Person{id=0, name=0}<-- second check
here:0
Run Code Online (Sandbox Code Playgroud)
你的equals()
方法是错的.无论其他人是什么,它都会返回true.
它不遵守equals()
BTW 的合同,因为相等的对象应该具有相同的hashCode,而hashCode是该人的ID.因此,具有不同ID的两个人具有不同的hashCode,但仍然是相等的.
也就是说,您的测试表明hashCode()执行了10次.但它并没有被执行contains()
.它由执行add()
.每次向对象添加对象时,hashCode()
都会使用它来知道哪个存储桶应该保存该对象.
归档时间: |
|
查看次数: |
189 次 |
最近记录: |