This class implements the SortedMap interface using an internal Red-Black tree data structure and guarantees that the keys and values of the mapping can be enumerated in ascending order of keys. treeMap supports all optional Map methods . The objects used as keys in a TReeMap must all be mutually Comparable , or an appropriate Comparator must be provided when the treeMap is created. Because treeMap is based on a binary tree data structure, the get( ) , put( ) , remove( ) , and containsKey( ) methods operate in relatively efficient logarithmic time. If you do not need the sorting capability of TReeMap , however, use HashMap instead, as it is even more efficient. See Map and SortedMap for details on the methods of treeMap . See also the related treeSet class. In order for a TReeMap to work correctly, the comparison method from the Comparable or Comparator interface must be consistent with the equals( ) method. That is, the equals( ) method must compare two objects as equal if and only if the comparison method also indicates those two objects are equal. The methods of treeMap are not synchronized . If you are working in a multithreaded environment, you must explicitly synchronize all code that modifies the treeMap , or obtain a synchronized wrapper with Collections.synchronizedMap( ) . Figure 16-63. java.util.TreeMap<K,V>public class TreeMap<K,V> extends AbstractMap<K,V> implements SortedMap<K,V>, Cloneable, Serializable { // Public Constructors public TreeMap ( ); public TreeMap (Comparator<? super K> c ); public TreeMap (SortedMap<K,? extends V> m ); public TreeMap (Map<? extends K,? extends V> m ); // Methods Implementing Map public void clear ( ); public boolean containsKey (Object key ); public boolean containsValue (Object value ); public Set<Map.Entry<K,V>> entrySet ( ); public V get (Object key ); public Set<K> keySet ( ); public V put (K key , V value ); public void putAll (Map<? extends K,? extends V> map ); public V remove (Object key ); public int size ( ); public Collection<V> values ( ); // Methods Implementing SortedMap public Comparator<? super K> comparator ( ); public K firstKey ( ); public SortedMap<K,V> headMap (K toKey ); public K lastKey ( ); public SortedMap<K,V> subMap (K fromKey , K toKey ); public SortedMap<K,V> tailMap (K fromKey ); // Public Methods Overriding AbstractMap public Object clone ( ); } |