这个是现学现用的。
public class Student {
private String name;
private int age;
public Student(int age) {
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;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student){
obj = (Student) obj;
return ((Student) obj).getName().equals(getName())? true:false;
}
return false;
}
}
//这个很重要 这个就是排序的比较器 在这里是根据学生的年龄来排序的
import java.util.Comparator;
/**
* 比较器
* @author DELL
*
*/
public class StudentCompartor implements Comparator
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.getAge()>o2.getAge()){ //升序
return 1;
}
return -1;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class CollectionCompareDemo {
public static void main(String[] args) {
List
list.add(new Student(20));
list.add(new Student(30));
list.add(new Student(10));
list.add(new Student(40));
Collections.sort(list, new StudentCompartor()); //排序 传入要排序的集合和比较器
Iterator
while(iterator.hasNext()){
System.out.println(iterator.next().getAge());
}
}
}
输出的结果是:
10
20
30
40