Add a 'comparator' field to TreeMap

This will be needed for Java-compatible serialization of tree maps.

Note that the field should be null when the TreeMap uses the default
comparator.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
This commit is contained in:
Johannes Schindelin 2013-10-30 13:23:42 -05:00
parent 884d0979a9
commit afe09e32de

View File

@ -11,24 +11,32 @@
package java.util; package java.util;
public class TreeMap<K,V> implements Map<K,V> { public class TreeMap<K,V> implements Map<K,V> {
private TreeSet<MyEntry<K,V>> set; private final Comparator<K> comparator;
private transient TreeSet<MyEntry<K,V>> set;
public TreeMap(final Comparator<K> comparator) { public TreeMap(Comparator<K> comparator) {
set = new TreeSet(new Comparator<MyEntry<K,V>>() { this.comparator = comparator;
public int compare(MyEntry<K,V> a, MyEntry<K,V> b) { initializeSet();
return comparator.compare(a.key, b.key);
}
});
} }
public TreeMap() { private void initializeSet() {
this(new Comparator<K>() { final Comparator<K> comparator = this.comparator != null ?
this.comparator : new Comparator<K>() {
public int compare(K a, K b) { public int compare(K a, K b) {
return ((Comparable) a).compareTo(b); return ((Comparable) a).compareTo(b);
} }
};
set = new TreeSet(new Comparator<MyEntry<K,V>>() {
public int compare(MyEntry<K,V> a, MyEntry<K,V> b) {
return comparator.compare(a.key, b.key);
}
}); });
} }
public TreeMap() {
this(null);
}
public String toString() { public String toString() {
return Collections.toString(this); return Collections.toString(this);
} }