我想根据卷号对数据对象列表进行排序。但下面的代码与比较无关。
错误:
prog.java:15: error: GFG is not abstract and does not override abstract method compare(Data,Data) in Comparator
class GFG implements Comparator {
^
prog.java:25: error: is not abstract and does not override abstract method compare(Data,Data) in Comparator
Collections.sort(list, new Comparator(){
^
prog.java:27: error: compare(Data,Data) in cannot implement compare(T,T) in Comparator
public String compare(Data o1, Data o2) {
^
return type String is not compatible with int
where T is a type-variable:
T extends Object declared in interface Comparator
prog.java:26: error: method does not override or implement a method from a supertype
@Override
^
prog.java:28: error: incompatible types: int cannot be converted to String
return o1.rollNumber.compareTo(o2.rollNumber);
^
5 errors
数据类-
class Data {
String name;
String rollNumber;
Data(String name, String rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
}
主要功能-
class GFG implements Comparator {
public static void main (String[] args) {
ArrayList list = new ArrayList();
list.add(new Data("Harshit","16ume017"));
list.add(new Data("Neha","16ume08"));
list.add(new Data("Akshit","16ucc017"));
list.add(new Data("Kshitiz","16ucs017"));
System.out.println("Without sorted: \n"+list+"\n");
Collections.sort(list, new Comparator(){
@Override
public String compare(Data o1, Data o2) {
return o1.rollNumber.compareTo(o2.rollNumber);
}
});
System.out.println("With sorted: \n"+list+"\n");
}
}
代码链接(Ide):https://ide.geeksforgeeks.org/eWws4NwIXU
回答开始:得票数 3因为compare方法返回int
而不是String
Collections.sort(list, new Comparator(){
@Override
public int compare(Data o1, Data o2) {
return o1.rollNumber.compareTo(o2.rollNumber);
}
});
或(Java 8+)
Collections.sort(list, (d1, d2) -> d1.rollNumber.compareTo(d2.rollNumber));
总结
以上是真正的电脑专家为你收集整理的使用比较器:抽象对java对象进行排序时出错,并且未覆盖抽象方法比较的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得真正的电脑专家网站内容还不错,欢迎将真正的电脑专家推荐给好友。
有话要说...