gpt4 book ai didi

java - 为什么每次添加新元素时 ArrayList 的 hashCode() 都会发生变化?

转载 作者:IT老高 更新时间:2023-10-28 20:56:38 24 4
gpt4 key购买 nike

根据我对ArrayList的理解,默认容量是10,当超过10时,它会创建一个新的对象,以新的容量等等..

所以出于好奇,我输入了以下程序来检查 hashcode() 中的 ArrayList 对象:

public class TestCoreJava {

public static void main(String [] args){

ArrayList al = new ArrayList();

for(int i=0;i<15;i++){

al.add("Temp"+i);
System.out.println("Hashcode for "+i+" element "+al.hashCode());
}
}
}

根据上述情况,当我没有为 ArrayList 设置初始容量时,默认值为 10。因此,在添加第 11 个元素时,它将创建一个新对象并增加 ArrayList 的容量。

当我打印 ArrayList 对象的哈希码时,它每次都会给出一个新的 hashcode()

下面是o/p:

Hashcode for 0 element 80692955
Hashcode for 1 element -1712792766
Hashcode for 2 element -1476275268
Hashcode for 3 element 1560799875
Hashcode for 4 element 1220848797
Hashcode for 5 element -727700028
Hashcode for 6 element -1003171458
Hashcode for 7 element -952851195
Hashcode for 8 element 607076959
Hashcode for 9 element 1720209478
Hashcode for 10 element -6600307
Hashcode for 11 element -1998096089
Hashcode for 12 element 690044110
Hashcode for 13 element -1876955640
Hashcode for 14 element 150430735

根据默认容量的概念,直到第 10 个元素它应该打印相同的 hashcode(),因为在此之前不需要创建新对象,但事实并非如此。

最佳答案

ArrayListhashCodeArrayList中存储的所有元素的hashCode的函数,所以当容量改变时它不会改变,每当你添加或删除一个元素或以改变其 hashCode 的方式改变其中一个元素时它都会改变。

这是 Java 8 的实现(实际上是在 AbstractList 中实现的):

public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}

顺便说一句,这是 List 接口(interface)的 hashCode() 的 Javadoc 中出现的确切代码:

int java.util.List.hashCode()

Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

int hashCode = 1;
for (E e : list)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());

关于java - 为什么每次添加新元素时 ArrayList 的 hashCode() 都会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35702631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com