对list进行排序
我们在List里存入一些对象,比如person对象,若想要让这些对象按他们的age属性大小排序,不用我们自己实现,java已经帮我们实现了,我们只要实现Comparator接口,重写其中的compare方法就好。
<span style="font-size: small;">public class Person { String name; int age; public Person(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; } } </span>
- <span style="font-size: small;">import java.util.Comparator;
- public class MyComparetor implements Comparator {
- // 按年龄排序
- // public int compare(Object o1, Object o2){
- // Person p1=(Person)o1;
- // Person p2=(Person)o2;
- // return (p2.getAge()-p1.getAge());
- // }
- // 按姓名排序
- public int compare(Object o1, Object o2){
- Person p1=(Person)o1;
- Person p2=(Person)o2;
- return (p1.getName().compareTo(p2.getName()));
- }
- }</span>
上面的compare方法会返回3种值, -1,0,1. 当第一个大于第二个的时候返回1,相等返回0,小于返回-1
按姓名排序中,用p1compareto p2是升序,反之是降序
测试类:
- <span style="font-size: small;">public static void main(String[] args) {
- // TODO Auto-generated method stub
- List list=new ArrayList();
- list.add(new Person("weichao",22));
- list.add(new Person("lb",20));
- list.add(new Person("sf",18));
- list.add(new Person("wj",30));
- Collections.sort(list,new MyComparetor());
- Person person = null;
- for(int i = 0; i < list.size(); i++){
- person = (Person) list.get(i);
- System.out.println("name:" + person.getName() + ",age:" + person.getAge());
- }
- }</span>
这是我找的方法,但是谁知道,有没有简单的方法对list进行排序?