List接口对应的集合本身就是有序的,按输入的顺序输出。但是想要按某一变量的从小到大顺序输出,就得借助于Comparator这个接口。
public void test6() {
// class A implements Comparable {
//
// }
Comparator t = new Comparator() {
@Override
public int compare(Object o1,Object o2) {
// TODO Auto-generated method stub
Employee s1 = null;
Employee s2 = null;
if(o1 instanceof Employee && o2 instanceof Employee) {
s1 = (Employee)o1;
s2 = (Employee)o2;
if(s1.getAge()>s2.getAge())return 1;
else if(s1.getAge()<s2.getAge())return -1;
else return 0;
}
throw new RuntimeException("不能比较");
}
};
List c = new ArrayList();
c.add(new Employee("张",10));
c.add(new Employee("李",11));
c.add(new Employee("王",12));
c.add(new Employee("减肥",13));
c.add(new Employee("成功",16));
Collections.sort(c, t); //比较,按t的操作进行排序
//迭代器,对大多数Collection都适用
Iterator iter = c.iterator();
while(iter.hasNext()) { //迭代器的每一行信息
Object o = iter.next(); //迭代器输出一行
Employee s = (Employee)o; //将输出的值转化成Student
System.out.println(s.getName()+" "+s.getAge());
}
}