Java中Comparator的用法

主讲人:王少华  QQ群号:483773664


在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口以达到我们想要的目标。

接下来我们模拟下在集合对象中对日期属性进行排序

一、实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package chapter07_11;
 
public class Person {
    private int age;
    private String name;
    public Person(){}
    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
     
}

二、实现Comparator接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PersonComparator implements Comparator{
    /**
     * 如果o1小于o2,返回一个负数;
     * 如果o1大于o2,返回一个正数;
     * 如果他们相等,则返回0;
     */
    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        if(p1.getAge()<p2.getAge())return -1;
        if (p1.getAge()>p2.getAge()) return 1;
        return 0;
    }
}

三、测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TestSort {
    public static void main(String[] args) {
        Person p1 = new Person(28,"zhangsan");
        Person p2 = new Person(25,"lisi");
        Person p3 = new Person(32, "wangwu");
        ArrayList list = new ArrayList();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        for(Object object:list ){
            Person person = (Person) object;
            System.out.println(person.getAge()+"--"+person.getName());
        }
        System.out.println("-----------------------------");
        Collections.sort(list,new PersonComparator());
        for(Object object:list ){
            Person person = (Person) object;
            System.out.println(person.getAge()+

0

收藏

imentors

105篇文章,8W+人气,0粉丝

Ctrl+Enter 发布

发布

取消

0

分享
imentors