-1

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?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 2
    How are you determining the address is the same? The object address should not change. But the internal structures that hold the items might. – Jonathan Wood Aug 17 '23 at 06:58
  • 3
    Two things. 1) You're probably looking at the hashcode of the ArrayList, not the hashcode of the internal array which the ArrayList owns, and which actually contains your elements. 2) The hashcode of an object is not its address. The GC will move objects around in memory to compact them, but the hashcodes of those objects will stay the same. For classes, it's basically just a random number which is stored in the object header – canton7 Aug 17 '23 at 07:00
  • 1
    See: https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs,19 – canton7 Aug 17 '23 at 07:03

2 Answers2

1
  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.
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

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.

Laks Tutor
  • 36
  • 4