java - Why HashSet or HashMap does not support position based accessed? However these class also store object in array of type enter -
i have checked in source code of hashmap @ grepcode.com , found store object hashcode in array.
transient entry[] table; public v put(k key, v value) { if (key == null) return putfornullkey(value); int hash = hash(key.hashcode()); int = indexfor(hash, table.length); (entry<k,v> e = table[i]; e != null; e = e.next) { object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { v oldvalue = e.value; e.value = value; e.recordaccess(this); return oldvalue; } } modcount++; addentry(hash, key, value, i); return null; } void addentry(int hash, k key, v value, int bucketindex) { entry<k,v> e = table[bucketindex]; table[bucketindex] = new entry<k,v>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); }
please suggest.
yes true internally hashmap/hashset uses arrays. neither saving or retrieval these arrays sequential. reason simple: these collections use hashing
decide bucket store , retrieve objects. hash calcualted each entry not sequential number. , hash of each element used store , retrieve entries these collections.
Comments
Post a Comment