arrilist陣列和collections儲存學生排序

想不起来好名字發表於2024-03-17
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<>();
Student s1 = new Student("zsf", 24);
Student s2 = new Student("jcs", 23);
Student s3 = new Student("zxt", 24);

arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);

Collections.sort(arrayList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = 0;
num = o1.getAge() - o2.getAge();
int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;


return num2;
}


});
for (Student s : arrayList) {
System.out.println("姓名 " + s.getName() + " 年齡" + s.getAge());
}

}
}

public class Student {
private String name;
private int age;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

相關文章