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:
The problem is that
ClassCastExceptioncan occur, because you don’t know the type of the elements.