[英]How to add comparator to inner class?
public class Prerequisites {
private class Course implements Comparator<Course> {
public String name;
public LinkedList<Course> requiredFor;
public LinkedList<Course> prerequisites;
Course(String name) {
requiredFor = new LinkedList<Course>();
prerequisites = new LinkedList<Course>();
this.name = name;
}
@Override
public int compare(Course c0, Course c1) {
Pattern p = Pattern.compile("[A-Z]*");
Matcher matcher0 = p.matcher(c0.name);
Matcher matcher1 = p.matcher(c1.name);
matcher0.find();
matcher1.find();
int courseNumber0 = Integer.parseInt(c0.name.substring(matcher0.end(),c0.name.length()));
int courseNumber1 = Integer.parseInt(c1.name.substring(matcher1.end(),c1.name.length()));
if(courseNumber0 > courseNumber1) {
return 1;
}
else if(courseNumber0 < courseNumber1) {
return -1;
}
else {
return matcher0.group().compareTo(matcher1.group());
}
}
@Override
public String toString(){
return this.name;
}
}
public void compare(String args[]) {
Course c0 = new Course("CSE110");
Course c1 = new Course("DSE110");
LinkedList<Course> courses = new LinkedList<Course>();
courses.add(c0);
courses.add(c1);
**Collections.sort(courses);** //gives compiler error
}
}
Why adding Collections.sort() for this inner class is not working ? 为什么为此内部类添加Collections.sort()不起作用? I am not able to figure that out from the compiler error.
我无法从编译器错误中找出原因。
You probably meant to implement Comparable
, not Comparator
. 您可能打算实现
Comparable
而不是Comparator
。
That's what the Collections#sort
method expects : 这就是
Collections#sort
方法所期望的 :
public static <T extends Comparable<? super T>> void sort(List<T> list)
您应该实现Comparable
而不是Comparator
。
Collections.sort(courses);
- If its the above, what you want to implement then its java.lang.Comparable
Interface that you want to implement, and not java.util.Comparator Interface. -如果是上述条件,
java.lang.Comparable
实现的内容是您要实现的java.lang.Comparable
接口,而不是java.util.Comparator接口。
- Moreover Comparable Interface
is used when you need to Sort the item on the basis of only one attribute. -此外,当您需要仅基于一个属性对项目进行排序时,将使用
Comparable Interface
。
But if you want to sort the items on the basis of more than one Attribute , then please implement java.util.Comparator Interface
. 但是,如果要基于多个属性对项目进行排序 ,请实现
java.util.Comparator Interface
。
Collections.sort(List l, Comparator<T> t);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.