Name

TreeMap<K,V>

Synopsis

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( ).

java.util.TreeMap<K,V>

Figure 16-63. java.util.TreeMap<K,V>

public class TreeMap<K,V> extends AbstractMap<K,V> ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.