java使用自定义对象作为map的key

查找key的顺序:
1.调用hashCode()计算对象的HashCode,看是否存在表中
2.如果存在表中,则调用equals()判断对象是否相同

需要重写HashCode和equals方法,如果使用Eclipse就非常简单
直接右键->Source->Generate hashCode() and equals(),选择需要作为比较的字段即可

public class Student
{
    private String name;
    private int age;
    
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}

你可能感兴趣的:(java使用自定义对象作为map的key)