【发布时间】:2018-10-06 04:00:09
【问题描述】:
当我尝试使用类似接口创建匿名内部时,出现编译错误。
//Code trying to create treeset using comparable
// compilation error
TreeSet<String> treeSet5 = new TreeSet<String>(new Comparable<String>() {
@Override
public int compareTo(String o) {
// TODO Auto-generated method stub
return 0;
}
});
// CE:The constructor TreeSet<String>(new Comparable<String>(){}) is undefined
我知道对于自定义排序我们需要使用比较器,但我很好奇为什么我们不能创建可比较的匿名类。
//Custom sorting: default sorting as String implements comparable
// below code is fine as its working as expected.
TreeSet<String> treeSet2 = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
【问题讨论】:
-
它告诉你:“构造函数 TreeSet
(new Comparable (){}) 是未定义的”。定义 public TreeSet(Comparable<String> comparable) { } -
使用 Comparator 而不是 Comparable
标签: java collections comparator icomparable