package aaa;
import java.util.*;
public class aaa {
public static void main(String[] args) {
List<Student> c = new ArrayList<Student>();
Student s1=new Student("zhang",1401, 20, "computer");
Student s2=new Student("liu",1402,19,"law");
Student s3=new Student("wang",1403,17,"mechanical");
Student s4=new Student("li",1409,16,"english");
c.add(s1);
c.add(s2);
c.add(s3);
c.add(1,s4);
for(Iterator<Student> it =c.iterator();it.hasNext();){
Student temp=it.next();
System.out.println(temp);
}
//第一种接口排序
Collections.sort(c);
for(Iterator<Student> it =c.iterator();it.hasNext();){
Student temp=it.next();
System.out.println("1--"+temp);
}
//第二种接口排序
Collections.sort(c,new Outcompare());
for(Iterator<Student> it =c.iterator();it.hasNext();){
Student temp=it.next();
System.out.println("2--"+temp);
}
//第三种排序匿名内部类不加泛型
Collections.sort(c,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Student w1 = (Student)o1;
Student w2 = (Student)o2;
return w1.getAge()-w2.getAge();
}
});
for(Iterator<Student> it =c.iterator();it.hasNext();){
Student temp=it.next();
System.out.println("3--"+temp);
}
//第三种排序匿名内部类加泛型
Collections.sort(c,new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
for(Iterator<Student> it =c.iterator();it.hasNext();){
Student temp=it.next();
System.out.println("4--"+temp);
}
}
}
package aaa;
public class Student implements Comparable {
private String name;
private int id;
private int age;
private String major;
public Student(String name, int id, int age, String major) {
super();
this.name = name;
this.id = id;
this.age = age;
this.major = major;
}
public int getAge() {
return age;
}
public String toString() {
return "Student [name=" + name + ", id=" + id + ", age=" + age + ", major=" + major + "]";
}
@Override
public int compareTo(Object o) {
Student s = (Student)o;
return this.age-s.getAge();
}
}
package aaa;
import java.util.Comparator;
public class Outcompare implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student w1 = (Student)o1;
Student w2 = (Student)o2;
return w1.getAge()-w2.getAge();
}
}