JAVA高级(五)------ Comparable和Comparator比较器

我们经常会遇到排序的需求,String类型和Integer类型JDK提供了排序方法:

public class ComparableTest {
    public static void main(String[] args) {
        Integer data [] = new Integer[] {6,5,2,8,5,1,6,4,6};
        Arrays.sort(data);
        System.out.println(Arrays.toString(data));
    }
}
[1, 2, 4, 5, 5, 6, 6, 6, 8]

但是如果我们要对某个自定义的类的对象进行排序,就需要定义比较规则才能进行比较和排序,而制定比较规则就需要比较器,主要的比较器分为Comparable和Comparator比较器。

Comparable比较器

class Item implements Comparable<Item>{
    private String name;
    private int num;
    public Item(String name, int num) {
        this.name = name;
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public int getNum() {
        return num;
    }

    @Override
    public int compareTo(Item item) {
        // 从小到大 :this‐o
        // 从大到小:o‐this
        return item.num - this.num;
    }
}

public class ComparableTest {
    public static void main(String[] args) {
        List<Item> list = new ArrayList<Item>();
        list.add(new Item("a", 21));
        list.add(new Item("b", 8));
        list.add(new Item("c", 1));
        list.add(new Item("d", 9));
        Collections.sort(list);
        list.forEach(it -> {
            System.out.println(it.getName() + " -> " + it.getNum());
        });
    }
}
a -> 21
d -> 9
b -> 8
c -> 1

其中,compareTo()方法进行排序规则的定义
// 从小到大 :this‐o
// 从大到小:o‐this
//比较方法升级:先根据数量排序,如果数量一样,根据名称排序
if (this.num!=o.num) {
return this.num - o.num;
} else {
return this.name.compareTo(o.name);
}
}
}

Comparator比较器

这个挽救型比较器,因为Comparable比较器是需要被比较的对象的类实现Comparable接口的,若在设计之初未考虑比较功能,后面发现需要比较功能,而又不能随意修改代码,就可以用Comparator比较器。
使用Comparator时不要求被比较的类实现Comparable接口,但是需要一个额外的比较器类。

class Items {
    private String name;
    private int num;
    public Items(String name, int num) {
        this.name = name;
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public int getNum() {
        return num;
    }
}

class ItemsComparator implements Comparator<Items> {
    @Override
    public int compare(Items o, Items o1) {
        return o.getNum() - o1.getNum();
    }
}

public class ComparatorTest {
    public static void main(String[] args) {
        List<Items> list = new ArrayList<Items>();
        list.add(new Items("a", 21));
        list.add(new Items("b", 8));
        list.add(new Items("c", 1));
        list.add(new Items("d", 9));
        Collections.sort(list, new ItemsComparator());
        list.forEach(it -> {
            System.out.println(it.getName() + " -> " + it.getNum());
        });
    }
}
c -> 1
b -> 8
d -> 9
a -> 21

Comparable和Comparator的区别

  • Comparable是在类定义时实现的父接口,comparaTo()用于定义比较规则
  • Comparator是挽救比较器,需要设置单独的比较器规则类,并实现Comparator接口,通过compare()方法实现比较规则的定义

实际开发中,若有比较需求,最好选用Comparable比较器。

发布了92 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41231928/article/details/103389755
今日推荐