How ArrayList address still the same after doubling the capacity?

66 views Asked by At

in c# ArrayList is a collection

ArrayList a = new ArrayList(); 
a.Add(4); // capacity = 4 and count = 1
a.Add(4); 
a.Add(4); 
a.Add(4); //there the capacity is 4 count=4 so Capacity will be doubled if I add new element 
//but when I add a new element  
a.Add(5);

the capacity will be 8 as a new array with double old capacity will be created and the elements in old array will be copied to this array but when I see the hash code of the array (address) I found it the same so how can arrayList define a new array at heap and copy element to it but the address still the same ?

I expect different memory locations at heap but I found them the same does garbage collector do something behind the scene?

2

There are 2 answers

0
Tim Schmelter On
  1. The hashcode has nothing to do with the address of the object in memory.
  2. ArrayList.GetHashCode uses Object.GetHashCode which uses RuntimeHelpers.GetHashCode(Object) which returns a hashcode to identify that object. But again, there is no relation to memory addresses.

List or arrays don't override Equals and GetHashCode, so what they contain has no relation to the hashcode. The default implementation(RuntimeHelpers.GetHashCode) doesn't care about a value of a field in the object. I don't know the exact implementation of it, the documentation also doesn't tell much about it, you just have to know that you can use it if you want to ensure that you don't get an overridden GetHashCode. So...

  • RuntimeHelpers.GetHashCode returns identical hash codes for identical object references. The exception proves the rule: for strings it actually cares about if it's interned or not.
  • An overridden GetHashCode should take the values of the object into account, so two equal objects should always have the same hashcode.
0
Laks Tutor On

The hash code is not a direct representation of the memory address. The ArrayList object remains at the same memory location even if its internal array changes. The old array will be garbage collected when it's no longer in use.