As per my understanding of ArrayList
, the default capacity is 10 and when it grows beyond 10, it will create a new object with new capacity and so on..
So out of curiosity, I typed following program to check hashcode()
for ArrayList
object:
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());
}
}
}
According to above scenario, when I am not setting Initial capacity for ArrayList
the default would be 10.
So while adding 11th element, it will create a new object and increase the capacity for ArrayList
.
When I print the hashcode for ArrayList
object, it is giving a new hashcode()
each time.
Following is the 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
According to the concept of default capacity, till 10th element it should have printed same hashcode()
as no new object needs to be created until that point, but it is not the case.