package test;
import java.util.Comparator;
public class Student implements Comparator<Student>{//comparator接口
private String name;
private int age;
public Student(String name,int age)
{
this.name=name;
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;
}
public int compare(Student o1, Student o2) {//重写compare方法
// TODO Auto-generated method stub
if(o1.getAge()>o2.age)
return 1;
else {
return -1;
}
}
}
主
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu1 = new Student("路人甲", 20);
Student stu2 = new Student("路人已", 18);
Student stu3 = new Student("路人丙", 16);
Student stu4 = new Student("路人丁", 19);
List<Student> students=new ArrayList<Student>();
students.add(stu1);
students.add(stu2);
students.add(stu3);
students.add(stu4);
System.out.println("排序前:");
for(Student stu:students)
{
System.out.println("姓名:"+stu.getName()+"年龄"+stu.getAge());
}//排序前
Collections.sort(students, stu1);
for(Student stu:students)
{
System.out.println("姓名:"+stu.getName()+"年龄"+stu.getAge());
}//排序前
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(1);
list.add(1);
for(int i:list)
{
System.out.println(i);
}
}
}