memory reallocation issue in Java ArrayList, HashSet and HashMap -


looked unofficial references, , want confirm here understanding correct. suppose adding new (unique) elements time time,

  1. arraylist<t> reallocate memory since memory needs continuous, when memory grow newly inserted elements exceeds threshold, reallocation of larger continuous memory space happen, , existing elements moved such newly allocated larger continuous memory space;
  2. hashset<t> , hashmap<t> has no such issue since memory of them not require continuous?

btw, if articles on these areas, appreciate refer well.

regards, lin

if checkout sourcecode of add(e e) method in arraylist<> in java 8 (jre 1.8.0_71), calls in method called ensurecapacityinternal(int mincapacity). i.e method called every time add in object arraylist. inturn calls in series of methods , if size of arraylist smaller hold newly added element, calls in method called grow(int mincapacity). method shown below:

/**      * increases capacity ensure can hold @ least      * number of elements specified minimum capacity argument.      *      * @param mincapacity desired minimum capacity      */     private void grow(int mincapacity) {         // overflow-conscious code         int oldcapacity = elementdata.length;         int newcapacity = oldcapacity + (oldcapacity >> 1);         if (newcapacity - mincapacity < 0)             newcapacity = mincapacity;         if (newcapacity - max_array_size > 0)             newcapacity = hugecapacity(mincapacity);         // mincapacity close size, win:         elementdata = arrays.copyof(elementdata, newcapacity);     } 

this create new array size 1.5 times more initial 1 , copies elements old array new one. proves point no. 1.

coming point no. 2, in case of hashmap<k,v>, special type of array hold key , value pairs. array slots called buckets. so, every object add hashmap, should override hashcode() , equals() method properly. when call put(k key, v value) method, inturn calls method called putval(int hash, k key, v value, boolean onlyifabsent, boolean evict) calculating #hash of key hash(object key) have passed. hash indicates bucket location value object shoud go. hence, array here indicates address blocks objects goes in. this thread explains in more detail. hope looking for.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -