[个人原创]关于java中对象排序的一些探讨(二)

时间:2023-03-09 04:08:43
[个人原创]关于java中对象排序的一些探讨(二)

2.  使用Collections.sort()方法

Collections类中提供了诸多静态方法,诸如addAll(),max()等等。当自己相对Collection接口下的类处理的时候,可以看看这个工具箱里有没有自己能直接使用的工具。

 import java.util.*;

 /**
* Created By IntelliJ IDEA
* User:LeeShuai
* Date:3/6/14
* Time:5:22 PM
*/
public class CollectionsTest {
public static void main(String[] args) {
List<Person> person = new LinkedList<Person>();
person.add(new Person("十八子", 60));
person.add(new Person("大大的灯泡", 24));
person.add(new Person("十八子", 24));
person.add(new Person("大连", 22));
person.add(new Person("beijing", 54));
Collections.sort(person, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int i = new Integer(o2.getAge()).compareTo(new Integer(o1.getAge()));
if (i != 0) {
return i;
}
return o1.getName().compareTo(o2.getName());
}
});
Iterator<Person> it=person.iterator();
while(it.hasNext()){
Person person1= it.next();
System.out.println(String.format("名字:%s,年龄:%d",person1.getName(),person1.getAge()));
}
} }

运行结果:

 名字:十八子,年龄:60
名字:beijing,年龄:54
名字:十八子,年龄:24
名字:大大的灯泡,年龄:24
名字:大连,年龄:22