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/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM