Java⾃定义排序
java集合的⼯具类Collections中提供了两种排序的⽅法,分别是:
1. Collections.sort(List list)
2. Collections.sort(List list,Comparator c)
第⼀种称为⾃然排序,参与排序的对象需实现comparable接⼝,重写其compareTo()⽅法,⽅法体中实现对象的⽐较⼤⼩规则,⽰例如下: 实体类:(基本属性,getter/setter⽅法,有参⽆参构造⽅法,toString⽅法)
1package test;
2
3public class Emp implements Comparable {
4
5private String name;
6private int age;
7public String getName() {
8return name;
9 }
10public void setName(String name) {
11this.name = name;
12 }
13public int getAge() {
14return age;
15 }
16public void setAge(int age) {
17this.age = age;
18 }
19public Emp() {
20super();
21 }
22public Emp(String name, int age) {
23super();
24this.name = name;
25this.age = age;
26 }
27 @Override
28public String toString() {
29return "Emp [name=" + name + ", age=" + age + "]";
30 }
31 @Override
32public int compareTo(Object o) {
33if(o instanceof Emp){//判断是否可以转换,不能则抛出异常
34 Emp emp = (Emp) o;
35// return Age();//按照年龄升序排序
36return this.Name());//换姓名升序排序
37 }
38throw new ClassCastException("不能转换为Emp类型的对象...");
39 }
40
41 }
显然这种⽅法限制较多,⼀般⽤第⼆种匿名内部类
1 Collections.sort(ans,new Comparator(){
2 @Override
3public int compare(Object a1, Object b1){
4if(a1 instanceof ArrayList && b1 instanceof ArrayList) {
5 ArrayList<TreeNode> a = (ArrayList<TreeNode>) a1;
java集合排序怎么实现6 ArrayList<TreeNode> b = (ArrayList<TreeNode>) b1;
7
8if (a.size() > b.size()) return -1;
9else if (a.size() == b.size()) return 0;
10else return 1;
11 }
12throw new ClassCastException("不能转换为ArrayList类型");
13 }
14 });
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论