Eu escrevi um exemplo de classificação de Java Array, aqui vou compartilhar para que todos aprendam juntos
A cópia do código é a seguinte:
pacote com.yonyou.test;
importar java.util.arraylist;
importar java.util.Collections;
importar java.util.comparator;
importar java.util.list;
Teste de classe pública {
public static void main (string [] args) {
Estudante zlj = novo aluno ("ding xiaoyu", 21);
Estudante dxy = novo aluno ("Zhao Si", 22);
Estudante CJC = novo aluno ("Zhang San", 11);
Estudante LGC = novo aluno ("Liu Wu", 19);
List <very Student> StudentList = new ArrayList <Dentul> ();
StudentList.add (ZLJ);
StudentList.add (DXY);
StudentList.add (CJC);
StudentList.add (LGC);
System.out.println ("classificado por ano:");
Coleções.sort (Lista de Students, new SortByage ());
para (estudante estudante: Lista de Students) {
System.out.println (Student.getName () + " /" + student.getage ());
}
System.out.println ("==========");
System.out.println ("classificado por nome");
Coleções.sort (StudentList, new SortByName ());
para (estudante estudante: Lista de Students) {
System.out.println (Student.getName () + " /" + student.getage ());
}
}
}
classe Sortbyage implementa o comparador {
public int compare (objeto O1, objeto O2) {
Aluno s1 = (aluno) O1;
Aluno s2 = (aluno) O2;
if (s1.getage ()> s2.getage ())
retornar 1;
else if (s1.getage () == s2.getage ()) {
retornar 0;
}
retornar -1;
}
}
classe SortbyName implementa o comparador {
public int compare (objeto O1, objeto O2) {
Aluno s1 = (aluno) O1;
Aluno s2 = (aluno) O2;
if (s1.getName (). compareto (s2.getName ()) <0)
retornar -1;
caso contrário, if (s1.getName (). compareto (s2.getName ())> 0) {
retornar 1;
}
retornar 0;
}
}
Classe Student {
private Int Age;
nome de string privado;
public int getage () {
idade de retorno;
}
Public Void Setage (Int Age) {
this.age = idade;
}
public String getName () {
Nome de retorno;
}
public void setName (nome da string) {
this.name = nome;
}
Public Student (nome da string, Int Age) {
this.age = idade;
this.name = nome;
}
}