What is the diff between a TreeMap vs. HashMap?

来源:互联网 发布:网络的发展与未来二课 编辑:程序博客网 时间:2024/06/07 15:14

Thelargest difference between the two is the underlying structure used in theimplementation.

HashMapsuse an array and a hashing function to store elements. When you try to insert ordelete an item in the array the hashing function converts the key into an indexon the array where the object is/should be stored (ignoring conflicts). Whilehashmaps are generally very fast because they don't need to iterate over largeamounts of data, they slow down when they're filled because they need to copyall the key/values into a new array.

TreeMapsstore a the data in a sorted tree structure. While this means that they'llnever have to allocate more space and copy over to it, operations require thatpart of the data already stored be iterated over. Sometimes changing largeamounts of the structure.

Out ofthe two Hashmaps will generally have better performance when you don't needsorting.

Insertiontime of HashMap is O(1) if the hash code disperses keys appropriately.

Insertion time of TreeMap is O(log(n)).
0 0
原创粉丝点击