Я хочу отсортировать список объектов данных по номеру рулона. Но следующий код не работает с сравнением.
Ошибка:
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