Thursday 15 August 2013

java - Hashmap Capacity not increased even on reaching threshold -



java - Hashmap Capacity not increased even on reaching threshold -

java doc says - when number of entries in hash table exceeds product of load factor , current capacity, hash table rehashed

in below programme -

hashmap<integer, string> map = new hashmap<integer, string>(); int = 1; while(i<16) { map.put(i, new integer(i).tostring()); i++; }

key of type integer, @ insertion of 13th 15th element hashmap capacity remains 16 , threshold remains same 12, why ?

debug screenshot after adding 13th element in map -

args string[0] (id=16) map hashmap<k,v> (id=19) entryset null hashseed 0 keyset null loadfactor 0.75 modcount 13 size 13 table hashmap$entry<k,v>[16] (id=25) threshold 12 values null 14 [null, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11, 12=12, 13=13, null, null]

hashmap key of type string - hashmap<string, string> or custom class - map<employee,integer> show expected behaviour @ 13th insertion

looks behaviour due alter in internal implementation of hashmap set method in recent version of java 7. after going through source code of multiple versions, found reply question

hashmap set method calls addentry() add together new entry -

public v put(k key, v value) { ... int hash = hash(key); int = indexfor(hash, table.length); ... addentry(hash, key, value, i); ... }

jdk7-b147 hashmap.addentry method looks -

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); }

source code of version 1.7.0_67-b01 looks -

void addentry(int hash, k key, v value, int bucketindex) { if ((size >= threshold) && (null != table[bucketindex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketindex = indexfor(hash, table.length); } createentry(hash, key, value, bucketindex); }

so, in recent versions of java, hashmap may not resized based on threshold alone. if bucket empty entry still go in without resizing hashmap

java 8 may have different behaviour, source code of version 8-b132 shows set re implemented -

put(k key, v value) { homecoming putval(hash(key), key, value, false, true); } putval(int hash, k key, v value, boolean onlyifabsent,boolean evict) { node<k,v>[] tab; node<k,v> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; .... } final node<k,v>[] resize() { //many levels of checks before resizing }

java doc may not updated java versions ! stephen

java hashmap threshold load-factor

No comments:

Post a Comment