gpt4 book ai didi

java - 使用比较器对 java 对象进行排序时出错 : Abstract and does not override abstract method compare

转载 作者:行者123 更新时间:2023-11-30 01:45:14 27 4
gpt4 key购买 nike

我想根据卷号对数据对象列表进行排序。但以下代码无法与比较器一起使用。

错误:

prog.java:15: error: GFG is not abstract and does not override abstract method compare(Data,Data) in Comparator
class GFG implements Comparator<Data> {
^
prog.java:25: error: <anonymous GFG$1> is not abstract and does not override abstract method compare(Data,Data) in Comparator
Collections.sort(list, new Comparator<Data>(){
^
prog.java:27: error: compare(Data,Data) in <anonymous GFG$1> 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<Data> {
public static void main (String[] args) {
ArrayList<Data> list = new ArrayList<Data>();
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<Data>(){
@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

最佳答案

因为compare方法返回 int 而不是 String

Collections.sort(list, new Comparator<Data>(){
@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 - 使用比较器对 java 对象进行排序时出错 : Abstract and does not override abstract method compare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com