有 Java 编程相关的问题?

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

java HashSet“contains”方法是如何工作的?

我使用了Set的两种实现:HashSet和TreeSet。我添加了10个元素,通过contains方法从集合中设置并查找对象。我看到它包含迭代所有对象的方法,尽管它找到了元素。出于性能原因,我感到困惑。为什么会这样?我该如何预防

我有个人课:

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;
    }
}

}

在主类中,我添加了10人对象,然后通过集合的第一个元素调用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());
            } 
        }
    }

结果:

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

共 (3) 个答案

  1. # 1 楼答案

    它不会遍历所有元素。为每个对象打印hashcode的原因是,在插入集合时需要计算hashcode

  2. # 2 楼答案

    你的equals()方法是错误的。不管对方是谁,它都会返回true

    顺便说一句,它不尊重equals()的约定,因为相同的对象应该有一个相同的hashCode,hashCode是人的ID。所以两个ID不同的人拥有不同的哈希代码,但仍然是平等的

    也就是说,您的测试显示hashCode()执行了10次。但它不是由contains()执行的。它由^{执行。每次向集合中添加一个对象时,它的hashCode()都会被用来知道哪个桶应该容纳该对象

  3. # 3 楼答案

    前10个打印可能用于插入代码,最后一个打印用于contains调用。我希望这可能会让你困惑