Java比较器

寒假计划第一步已经完成,现在开始第二步。有时候我们计划达成某个大目标是很难而且很容易放弃的,一个好的方法就是制定一个个小目标,每个尽量明确且容易达到,这样我们每完成一项都会有成就感并驱使我们继续下去,就这样不知不觉,我们就完成了所有目标。

最近就在开始整理java基础知识,一边搜资料看视频,一边记录整理,还是挺不错的。

就在整理集合框架这部分时,想写一篇博客,所以就简单说一下比较器!

提要

在使用集合工具类进行排序时,通常都已经默认了排序方式(简单类型的排序),如果要进行对象集合的排序,就需要用到比较器。下面介绍了两种方法。

内部比较器(Comparable)

实现Comparable接口的compareTo方法,重点是返回值-1,0,1

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class People implements Comparable {
int sno;
String name;
int score;

...

@Override
public int compareTo(Object o) {
People p=(People) o;
int result=this.sno>p.sno? 1:(this.sno==p.sno?0:-1);//优化后Integer.compare(this.sno, p.sno);
return result;
}
}

在用IDEA编辑int result=this.sno>p.sno? 1:(this.sno==p.sno?0:-1);时,这片代码显示黄色,表示可以优化,优化后为int result= Integer.compare(this.sno, p.sno);,好奇地点开Integer.compare()方法,看到下面的源码

1
2
3
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

当然前面还有源码注解。因为默认排列及是升序,所以如果想要升序排列就采用上面的编写方法,相反,降序位置调换一下即可。

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test0 {
public static void main(String[] args) {
List<People> peopleList=new ArrayList<>();
peopleList.add(new People(1,"zy",95));
peopleList.add(new People(6,"ls",86));
peopleList.add(new People(16,"ww",75));
peopleList.add(new People(25,"zl",63));
peopleList.add(new People(3,"ao",55));
peopleList.add(new People(9,"xp",13));

Collections.sort(peopleList);//排序

System.out.println(peopleList);
}
}

输出

1
[People{sno=1, name='zy', score=95}, People{sno=3, name='ao', score=55}, People{sno=6, name='ls', score=86}, People{sno=9, name='xp', score=13}, People{sno=16, name='ww', score=75}, People{sno=25, name='zl', score=63}]

外部比较器(Comparator)

定义外部比较器,实现Comparator接口的compare方法

实例

1
2
3
4
5
6
7
8
public class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
People p1= (People) o1;
People p2= (People) o2;
return p1.sno-p2.sno;
}
}

没啥可说的,升序就按上面来,当然也可按上面的来,返回-1,0,1

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test0 {
public static void main(String[] args) {
List<People> peopleList=new ArrayList<>();
peopleList.add(new People(1,"zy",95));
peopleList.add(new People(6,"ls",86));
peopleList.add(new People(16,"ww",75));
peopleList.add(new People(25,"zl",63));
peopleList.add(new People(3,"ao",55));
peopleList.add(new People(9,"xp",13));

Collections.sort(peopleList,new MyComparator());//排序

System.out.println(peopleList);
}
}

输出(同上)

1
[People{sno=1, name='zy', score=95}, People{sno=3, name='ao', score=55}, People{sno=6, name='ls', score=86}, People{sno=9, name='xp', score=13}, People{sno=16, name='ww', score=75}, People{sno=25, name='zl', score=63}]

参考

https://www.bilibili.com/video/BV114411W7id?p=47

比较

  • 使用方法不同,目的相同(排序嘛)
  • Comparable在类的内部,与类粘连在一块,也比较容易实现
  • Comparator在类的外部,自己额外定义,实现数据与算法分离
  • 我个人认为无所谓用哪个,顺手就行