如何在构造函数内实例化比较器
我从未见过在 TreeMap 结构的构造函数内部创建比较器。人们会如何去做这件事呢?有没有办法让 TreeMap() 构造函数调用另一个具有比较器参数的 TreeMap 构造函数来设置比较器?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们通常将该字段设置为 null,而不是实例化某些内容。
但如果您愿意,您可以:
问题是可能会发生
ClassCastException
,因为您不知道元素的类型。They usually set that fields to
null
, rather than instantiating something.But if you want to, you can have:
The problem is that
ClassCastException
can occur, because you don't know the type of the elements.