[英]Anonymous inner class using Comparable interface
当我尝试使用可比接口创建匿名内部时,出现编译错误。
//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);
}
});
可比用于创建可以与自己进行比较的类。
比较器将与未实现Comparable的类一起使用(无论出于何种原因,例如,来自第三方),或者您要与原始的compareTo()方法进行比较而不比较它们而不继承它们。
希望对您有意义。
这是精心制作的示例: https : //www.geeksforgeeks.org/comparable-vs-comparator-in-java/
TreeSet
类的Util类进行排序需要Comparator
因为它具有两个可以比较的参数。 Comparable
没有足够的信息来与其他元素进行比较。 问:现在,您将问当Sorting Item实现Comparable
时它如何工作?
答:在这种情况下,排序项目是要与之进行比较的第一个项目,其他元素传递给其方法compareTo(String o)
实际上,一旦我看到TreeSet API,我就会在下面意识到。
上面的错误是因为TreeSet不接受Comparable接口作为构造函数参数,它只接受带有实现的Comparator接口。
Treeset treeSet=new TreeSet();
//Creates empty tree set. All objects are inserted according to natural sorting order.
Treeset treeSet=new TreeSet(Comparator c);
//Creates empty treeSet object, objects are maintained according to defined Comparator.
TreeSet treeSet = new TreeSet(Collection c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.