java - Best HashMap initial capacity while indexing a List -


i have list (list<t> list) , want index objects ids using map (hashmap<integer, t> map). use list.size() initial capacity in hashmap constructor,like in code below. best initial capacity used in case?

note: i'll never add more items map.

list<t> list = mylist; map<integer, t> map = new hashmap<integer, t>(list.size()); for(t item : list) {     map.put(item.getid(), item); } 

if wish avoid rehashing hashmap, , know no other elements placed hashmap, must take account load factor initial capacity. load factor for hashmap defaults 0.75.

the calculation determine whether rehashing necessary occurs whenever new entry added, e.g. put places new key/value. if specify initial capacity of list.size(), , load factor of 1, rehash after last put. prevent rehashing, use load factor of 1 , capacity of list.size() + 1.

edit

looking @ hashmap source code, rehash if old size meets or exceeds threshold, won't rehash on last put. looks capacity of list.size() should fine.

hashmap<integer, t> map = new hashmap<integer, t>(list.size(), 1.0); 

here's relevant piece of hashmap source code:

void addentry(int hash, k key, v value, int bucketindex) {     entry<k,v> e = table[bucketindex];     table[bucketindex] = new entry<>(hash, key, value, e);     if (size++ >= threshold)         resize(2 * table.length); } 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -