| Start |
|---|
| TreeMap of a simple Java type First, we create an empty map, and insert some elements into it: Once we have a few elements in the map, we can perform some operations: We can also iterate over the map elements using either an Iterator, or a foreach loop. Note that the entries are printed according to their natural ordering (opens new window), not the insertion order: |
| TreeSet of a simple Java Type First, we create an empty set, and insert some elements into it: Once we have a few elements in the set, we can perform some operations: We can also iterate over the map elements using either an Iterator, or a foreach loop. Note that the entries are printed according to their natural ordering (opens new window), not the insertion order: |
| TreeMap/TreeSet of a custom Java type Since Say we have a custom If we store it as-is in a Then we'd run into an Exception such as this one: To fix that, let's assume that we want to order However, there are two caveats to both approaches: The implementor must ensure `sgn(x.compareTo(y)) == -sgn(y.compareTo(x))` for all x and y. (This implies that `x.compareTo(y)` must throw an exception iff `y.compareTo(x)` throws an exception.) The implementor must also ensure that the relation is transitive: `(x.compareTo(y)>0 && y.compareTo(z)>0)` implies `x.compareTo(z)>0`. Finally, the implementor must ensure that `x.compareTo(y)==0` implies that `sgn(x.compareTo(z)) == sgn(y.compareTo(z))`, for all z. |
| TreeMap and TreeSet Thread Safety
Both However, if read and modified concurrently, or modified concurrently by more than one thread, the collection might throw a ConcurrentModificationException (opens new window) or behave unexpectedly. In these cases, it's imperative to synchronize/lock access to the collection using one of the following approaches: This will provide a SortedSet (opens new window)/SortedMap (opens new window) implementation backed by the actual collection, and synchronized on some mutex object. Note that this will synchronize all read and write access to the collection on a single lock, so even concurrent reads would not be possible. ... ... ... ... As opposed to the previous synchronization methods, using a ReadWriteLock (opens new window) allows multiple threads to read from the map concurrently. |
Read Article
https://develop.horje.com/learn/1434/reference