I have never seen a comparator created inside of a constructor for a TreeMap structure. How would one go about doing this? Is there a way to make the TreeMap() constructor call the other TreeMap constructor which has a comparator argument to set up the comparator?
private Comparator<? super K> cmp;
private Node root;
private int size;
private final String indentStr = " ";
public TreeMap() {
// Create cmp assuming K implements Comparator
//??? TreeMap(new Comparator<V>());
}
public TreeMap(Comparator<? super K> cmp) {
this.cmp = cmp;
}
They usually set that fields to null
, rather than instantiating something.
But if you want to, you can have:
this(new Comparator<K>() {
public int compare(K k1, K k2) {
return ((Comparable<K>) k1).compareTo(k2);
}
});
The problem is that ClassCastException
can occur, because you don't know the type of the elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.