gpt4 book ai didi

Java错误eclipse列表排序

转载 作者:行者123 更新时间:2023-12-01 06:50:22 25 4
gpt4 key购买 nike

我在以下行中遇到错误:

Collections.sort(l);

你能解释一下为什么吗?

这是程序代码:

import java.io.*;
import java.util.*;

public class Esame{

public static void main(String args[]) throws IOException{
ArrayList<Studente> l=new ArrayList<Studente>();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
String cognome = b.readLine();
while(!cognome.equals("")){
System.out.println("inserire nome");
String nome = b.readLine();
System.out.println("inserire matricola");
String matricola = b.readLine();
Studente s = new Studente(nome, cognome, matricola);
l.add(s);
System.out.println("inserire cognome");
cognome = b.readLine();
}
b.close();
Collections.sort(l);
Iterator<Studente> i=l.iterator();
PrintStream p=new PrintStream(new File("uscita.txt"));
while(i.hasNext()){
p.println(i.hasNext());
}
p.close();
}

}

class Studente{

protected String nome,cognome;
protected int matricola;

public Studente(String nome,String cognome,String matricola){
this.nome=nome;
this.cognome=cognome;
this.matricola=Integer.parseInt(matricola);
}

public String toString(){
return "\n NOME: "+nome+"Cognome: "+cognome+"MATRICOLA: "+matricola;
}

public int compareTo(Object x) {
Studente p = (Studente) x;
return cognome.compareTo(p.cognome);
}
}

最佳答案

您只需 implements Comparable<T>要解决问题,或者您可以传递 Comparatorsort方法,如:

Collections.sort(l, new Comparator<Studente>() {
@Override
public int compare(Studente o1, Studente o2) {
// some kind of comparation
return o1.matricola - o2.matricola;
}
});

这样你的类就不需要实现 Comparable 接口(interface)

关于Java错误eclipse列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343483/

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