重写 Immutable 类的 hashCode 和 equals 方法

问题描述 投票:0回答:1

假设我有一个不可变的类,其中包含一个字符串和一个列表,如下所示

public final class Immutable {
    private final String a;
    private final List<String> list;

    public Immutable(String a, List<String> list){
        this.a=a;
        this.list = Collections.unmodifiableList(list);
    }

    public String getA(){
        return a;
    }

    public List<String> getList(){
        return list;
    }

}

基于不可变对象的知识,我应该在 hashcode() 和 equals() 方法中编写什么,以提高效率,即使用 new 关键字创建的两个不可变对象永远不相等。

我可以编写 equals() 和 hashcode() 方法吗:

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

    if (obj.getClass() != this.getClass()) {
        return false;
    }        
    if(this == obj){
        return true;
    }

    return false;
}

@Override
public int hashCode() {
    return Objects.hash(a);
}

我的所有测试用例都使用此代码运行良好。

java equals hashcode
1个回答
0
投票

基于不可变对象的知识,我应该在 hashcode() 和 equals() 方法中编写什么,以提高效率,即使用 new 关键字创建的两个不可变对象永远不相等。

没什么。

您可以从继承自

Object
的实现中免费获得这些语义。

© www.soinside.com 2019 - 2024. All rights reserved.