现象:
list如何按照自定义排序
方法:
一:list有序列表 输出按照放入先后排序
二:使用Collections.sort()排序
三:创建对象
四:
发现,代码直接报错了:
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Person>). The inferred type Person is not a valid substitute for the bounded
parameter <T extends Comparable<? super T>>
从上面可知,Person不是一个有效的参数类型,而应该extends Comparable。
要排序需要有排序的规则,要有比较。Inteage这个对象已经帮我们实现了Comparable接口,所以Inteage类型自己就是可以比较的。而我们的Student如果想要排序,也必须能够按某种规则进行比较,也就是要实现一个比较器。我们可以通过实现Comparable或Comparator接口实现比较器 。
Interage实现了接口
五:Comparable实现排序 :实体类Student需要implements Comparable,然后重写compareTo方法,在此方法里实现比较规则
实现接口重写方法之后实现排序
六:Comparator实现排序:Comparator实现比较器,是定义在Person类的外部的,因此实体类Person不需要做任何变化
排序输出:
七:使用内部类重新方法来实现通过对象某个参数来排序
stockChangeDetails 是需要排序的list ,通过重写compare的方法来自定义排序:方法返回-1 就会调换o1和o2的循序 返回0或者1 则不会改变