当仅等于被覆盖时,为什么列表找到项为true?

时间:2019-05-13 01:55:02

标签: java hashmap hashtable equals hashcode

我知道哈希码和等号都需要被覆盖。我尝试了下面的程序,想知道为什么列表设置时不能搜索学生,而仅覆盖等于时不能搜索学生:

import java.util.*;

class Student {
private int id;
private String name;

public Student(int id, String name) {
    this.name = name;
    this.id = id;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) return false;

    if (!(obj instanceof Student))
        return false;

    if (obj == this)
        return true;

    return this.getId() == ((Student) obj).getId();
}
}

public class StudentHashcodeEquals {
public static void main(String[] args) {
    Student alex1 = new Student(1, "Alex");
    Student alex2 = new Student(1, "Alex");

    System.out.println("alex1 hashcode = " + alex1.hashCode());
    System.out.println("alex2 hashcode = " + alex2.hashCode());
    System.out.println("Checking equality between alex1 and alex2 = " + alex1.equals(alex2));

    List<Student> studentsLst = new ArrayList <Student>();
    studentsLst.add(alex1);
    studentsLst.add(alex2);

    System.out.println("Arraylist size = " + studentsLst.size());
    System.out.println("Arraylist contains Alex = " + studentsLst.contains(new Student(1, "Alex")));

    HashSet <Student> students = new HashSet <Student>();
    students.add(alex1);
    students.add(alex2);

    System.out.println("HashSet size = " + students.size());
    System.out.println("HashSet contains Alex = " + students.contains(new Student(1, "Alex")));
}
}

/*
alex1 hashcode = 366712642
alex2 hashcode = 1829164700
Checking equality between alex1 and alex2 = true
Arraylist size = 2
Arraylist contains Alex = true
HashSet size = 2
HashSet contains Alex = false
*/

当将学生插入到列表中时,我假设将其插入2个不同的存储桶中,因为哈希码实现不存在,默认对象哈希码将被插入,并将其存储到2个不同的哈希码中,当搜索另一个对象时,它必须首先通过哈希码找到存储桶,但是哈希码实现不存在,然后列表如何仍然能够识别它,而set则不能?

谢谢!

1 个答案:

答案 0 :(得分:0)

列表不使用对象的哈希码。根据它们的类型,它们存储对对象的引用数组。

如果您在列表上调用contains,它将使用.equals()遍历列表,以检查对象是否在列表中。