/**
要對List<Student>進(jìn)行排序(按照年齡由小到大)
collections工具類可比較大小對集合進(jìn)行排序 實(shí)現(xiàn)Comparble實(shí)現(xiàn)Comparator
collection接口 子接口:list set
1.要實(shí)現(xiàn)Comparable<T>接口
int compare To(T o) o--要比較的對象
2.要實(shí)現(xiàn)Comparator<Student>接口 java.util
int compare(T o1, T o2) 比較用來排序的兩個參數(shù)壶冒。
比較此對象與指定對象的順序截歉。如果該對象小于、等于或大于指定對象咸作,則分別返回負(fù)整數(shù)宵睦、零或正整數(shù)。
@author Administrator
*/
//根據(jù)元素的自然順序(由小到大) 對指定列表按升序排序状飞。
Collections.sort(list);
Iterator<Student>iterator=list.iterator();
while(iterator.hasNext()) {
Student student=iterator.next();
System.out.println(student.getName()+"---"+student.getAge());
}
System.out.println("--------------------------------------");
//由大到小排序
Comparator<Student> comparator=Collections.reverseOrder();
Collections.sort(list, comparator);
Iterator<Student>it=list.iterator();
while(it.hasNext()) {
Student student=it.next();
System.out.println(student.getName()+"---"+student.getAge());
}
System.out.println("----------------------------------------");
//根據(jù)姓名來排序
Collections.sort(list,new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getName().compareTo(o2.getName());
}
});
Iterator<Student>it1=list.iterator();
while(it1.hasNext()) {
Student student=it1.next();
System.out.println(student.getName()+"---"+student.getAge());
}