将0作为哈希码返回是否安全

时间:2014-03-21 10:59:36

标签: java hashcode

我有一个有文章列表(或你想要的)的类。如下所示,实现/覆盖该类中的hashCode()函数是否安全:

class Place{
    List <Article> list = new List<Article>();

    public int hashCode() {
        if(list.isEmpty())
            return 0; //is it safe to return 0
        else
            return list.get(0).hashCode();
    }
}

public class Main{
    private HashSet<Place> places = new HashSet<>();

    //this function must be donne like this
    public boolean isArticleIn(Article article){
        Place place = new Place();
        place.add(article);
        return places.contains(place);
    }
}

是否有可能有一个非空的列表并返回0。

2 个答案:

答案 0 :(得分:3)

如果要将类的对象存储在使用hashCode的容器中,则应确保"if two objects are equal then they should return the same hash code"(否则容器可能存储重复项/通常会混淆)。如果它们都有一个空列表,那么你的类的对象会比较相等吗?

关于如何实现equals和hashcode以便在保持一致性的同时捕获所需信息的最佳建议是available here(使用推荐的Apache Commons Lang库中的EqualsBuilder和HashCodeBuilder)。列表中的所有元素似乎都应该对哈希码做出贡献 - 毕竟,如果列表的第二个或第三个元素不同,那么您的对象将从等于&#39;等于&#39; - 对吗?

答案 1 :(得分:1)

很安全。这是不可改变的,这很好。

然而您的散列集合将不具备高效性,因为您不提供均匀分布的散列码范围,因此您的散列填充不会均匀分布。请参阅here for an explanation of what's going on inside a hashed collection

相关问题