ArrayList中对象 排序

public class Student implements Comparable {
private String studentname;
public int studentage; public Student(String studentname, int studentage) {
this.studentname = studentname;
this.studentage = studentage;
} @Override
public int compareTo(Object comparestu) {
int compareage=((Student)comparestu).studentage;
/* For Ascending order*/
return this.studentage-compareage; } @Override
public String toString() {
return "[ name=" + studentname + ", age=" + studentage + "]";
} }
import java.util.ArrayList;
import java.util.Collections; public class ArrayListSorting {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student( "Chaitanya", 26));
arraylist.add(new Student( "Rahul", 24));
arraylist.add(new Student( "Ajeet", 32));
arraylist.add(new Student( "aa", 10)); Collections.sort(arraylist); for(Student str: arraylist){
System.out.println(str);
}
}
} ref:
https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/
上一篇:Umbraco 上传文件到另一个文件夹,而不是media files


下一篇:Snippet: Fetching results after calling stored procedures using MySQL Connector/Python