类排序

方法一:实现Comparable接口

public class Person implements Comparable<Person>
{
    String name;
    int age;
    public Person(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
    }
    
    @Override
    public int compareTo(Person p)
    {
        return this.age-p.getAge();
    }
    
}

 

public static void main(String[] args)
    {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("排序前");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
        Arrays.sort(people);
        System.out.println("\n排序后");
        for (Person person : people)
        {
            System.out.print(person.getName()+":"+person.getAge());
        }
    }

 

方法二:comparator

Item[] items=new Item[]{new Item(3L, "aaaa"),new Item(2L, "bbbbb")};

System.out.println("排序前");
for (Item item : items)
{
System.out.print(item.getId()+":"+item.getDesc());
}

Arrays.sort(items, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.getId().compareTo(o2.getId());
}
});

System.out.println("\n排序后");
for (Item item : items)
{
System.out.print(item.getId()+":"+item.getDesc());
}

 

posted @ 2019-05-05 15:09  三尺墨  阅读(184)  评论(0编辑  收藏  举报