Difference between HashMap, TreeMap and LinkedHashMap in Java

114 阅读1分钟

1. Implementation Details

The HashMap and LinkedHashMap classes implements the Map interface, whereas TreeMap implements the Map, NavigableMap, and SortedMap interface. A HashMap is implemented as Hash table, a TreeMap is implemented as Red-Black Tree, and LinkedHashMap is implemented as doubly-linked list of Buckets in Java.

public class TreeMap<K,V>    extends AbstractMap<K,V>    implements 
NavigableMap<K,V>, Cloneable, java.io.Serializable
//TreeMap实现了NavigableMap
public interface NavigableMap<K,V> extends SortedMap<K,V> 
//NavigableMap继承了SortMap

TreeMap底层的数据结构是红黑树,LinkedHashMap的底层结构是双向链表

2. Performance

Assuming the hash function disperses the elements properly among the buckets, HashMap and LinkedHashMap offers O(1) time performance for the basic operations such as get, put, containsKey, remove, etc. On the other hand, TreeMap guarantees O(log(n)) time cost for these operations.

执行get, put, containsKey, remove 等操作,LinkedHashMap的时间复杂度为O(1),TreeMap的时间复杂度为O(log(n))

3. Null values/keys

HashMap and LinkedHashMap permits null values and null key, whereas TreeMap permits only null values (not null keys) if natural ordering of keys is used. It supports null keys only if its Comparator supports comparison on null keys.

==>HashMap和LinkedHashMap允许的值和键,TreeMap只允许存在空的值,不允许存在空的键