简体   繁体   中英

Why Java doesn't use ArrayList class to implement Hashtable/HashMap class?

This QA How does Java implement hash tables? describes that Hashtable is implemented via static array in Java (the underlying static array will be refined according to the total number of items).

Why doesn't Java implement Hashtable via dynamic array, such as ArrayList?

What are the tradeoffs?

When a hashtable is resized, all of the entries need to be re-positioned.
Using an ArrayList would therefore be slower , since the ArrayList would copy over the now-useless old values before the HashTable re-calculates them all.

Resizing the underlying array requires rehashing all items in the hashtable, which is a very costly operation and invalidates the position of any item currently in the array - that's why you usually double the array size everytime the number of items exceeds a certain threshold (the load factor). Since resizing is managed internally and existing items have to be moved to a new position anyway a "resizable array" like ArrayList doesn't make sense.

Implementation classes are quite opaque. Since an ArrayList is rather uneffcient compared to a real static array there's no need to use it.

You won't have any benefit, at least in this way you save up having a wrapper to the static array that contains the hash map.

Resizing an ArrayList would be like resizing an HashMap , since they both work with a static underlying array but you'll need to rehash all the elements of the map in any case so there's really no need to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM