ArrayList<class>中,class有int学号属性和String班级属性,怎么样按学号升序输出?
时间: 2024-02-28 07:55:05 浏览: 63
你可以使用`Comparator`接口来定义按学号升序排序的规则,并使用`Collections.sort()`方法来排序。以下是示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
private int id;
private String className;
public Student(int id, String className) {
this.id = id;
this.className = className;
}
public int getId() {
return id;
}
public String getClassName() {
return className;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(3, "A"));
students.add(new Student(1, "B"));
students.add(new Student(2, "C"));
Comparator<Student> comparator = Comparator.comparing(Student::getId);
Collections.sort(students, comparator);
for (Student student : students) {
System.out.println("id: " + student.getId() + ", className: " + student.getClassName());
}
}
}
```
输出结果为:
```
id: 1, className: B
id: 2, className: C
id: 3, className: A
```
阅读全文