With TreeSets the key must be embedded in the object you store in the collection. Often you might have TreeSet of Strings. All you can do then is tell if a given String is in the Set. It won’t find you an associated object he way a Treemap will. With a TreeMap the keys and the objects they are associated with are separate.
TreeMap and its brother TreeSet oddly have nothing to do with representing trees. Internally they use a tree organisation to give you an alphabetically sorted Map/Set, but you have no control over links between parents and children.
Internally TreeMap uses red-black trees. There is no need to presort the data to get a well-balanced tree. On the other hand, if the data are sorted (ascending or descending), it won’t hurt as it does with some other types of tree.
The TreeMap will be sorted by the natural order of the key, i.e. by its implemented Comparable interface. If you want to keep it sorted in some other order, implement a Comparator< TypeOfKey> and pass that to the TreeMap constructor.
If you don’t supply a Comparator to define the ordering you want, TreeMap requires a Comparable implementation on the item class to define the natural order.
When you don’t know the precise key, you can use lowerKey, ceilingKey and higherKey to find it. You can also logically extract subsets of the map on a range of keys with subMap.
This page is posted
Optional Replicator mirror
Your face IP:[22.214.171.124]
You are visitor number|