我想根據卷号對數據對象列表進行排序。但下面的代碼與比較無關。
錯誤:
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對象進行排序時出錯,并且未覆蓋抽象方法比較的全部内容,希望文章能夠幫你解決所遇到的問題。
如果覺得真正的電腦專家網站内容還不錯,歡迎将真正的電腦專家推薦給好友。
有話要說...