小编Hon*_*hen的帖子

为什么Java实现Set和ArrayList的不同哈希码方法?

 // this is the hashCode method of Set
public int hashCode() {
    int h = 0;
    Iterator<E> i = iterator();
    while (i.hasNext()) {
        E obj = i.next();
        if (obj != null)
            h += obj.hashCode();
    }
    return h;
}



//this is the hashCode method of List
public int hashCode() {
    int hashCode = 1;
    for (E e : this)
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    return hashCode;
}
Run Code Online (Sandbox Code Playgroud)

为什么Java使用这两种不同的方法?有什么与Set and List的特征有关的东西吗?为什么使用31但不使用其他数字?谢谢!

java hashcode

4
推荐指数
1
解决办法
1430
查看次数

标签 统计

hashcode ×1

java ×1