我是靠谱客的博主 俏皮路灯,这篇文章主要介绍Java中的自然排序和比较器排序,现在分享给大家,希望可以做个参考。

写在前面的话:刚开始学习着两者排序时我也是一头雾水,虽然能写出来但是稀里糊涂,几时该用哪个排序一点想法都没有,后来经过研究这两者的作用点不同,自然排序作用在实体类上,而比较器排序作用在装实体类的集合上。

1、自然排序:java.lang.Comparable 

Comparable 接口中只提供了一个方法: compareTo(Object obj) ,该方法的返回值是 int 。如果返回值为正数,则表示当前对象(调用该方法的对象)比 obj 对象“大”;反之“小”;如果为零的话,则表示两对象相等。

总结为一句话:实现Comparable,重写 compareTo方法

案列:以TreeMap为例,默认的升序,可以重写自然排序的方法改变原有排序

复制代码
1
2
3
4
5
6
7
8
9
10
public static void testComparable(){         TreeMap<Car,Object> tmp = new TreeMap<Car,Object>();         tmp.put(new Car(4), "肆");         tmp.put(new Car(1), "壹");         tmp.put(new Car(5), "伍");         tmp.put(new Car(3), "三");         tmp.put(new Car(2), "贰");         System.out.println(tmp);         //结果://{Car [price=5.0]=伍, Car [price=4.0]=肆, Car [price=3.0]=三, Car [price=2.0]=贰, Car [price=1.0]=壹}     }

//自定义TreeMap排序方法    自然排序   

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Car implements Comparable<Car>{     private double price;          public double getPrice() {         return price;     }     public void setPrice(double price) {         this.price = price;     }     public Car(int price) {         super();         this.price = price;     }     @Override     public int compareTo(Car o) {         // TODO Auto-generated method stub         if(this.price>o.getPrice()){             return -1;//大的往前排         }else if(this.price<o.getPrice()){             return 1;//小的往后排         }else{             return 0;         }     }     @Override     public String toString() {         return "Car [price=" + price + "]";     }

2、比较器排序:java.util.Comparator 

总结为一句话:实现Comparator 接口,重写compare方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void testComparator(){         //HashMap<Integer,Object> hm = new HashMap<Integer,Object>();         TreeMap<Integer,Object> tmp = new TreeMap<Integer,Object>(new MyComparatorBigtoSmall());         tmp.put(4, "肆");         tmp.put(1, "壹");         tmp.put(5, "伍");         tmp.put(3, "三");         tmp.put(2, "贰");         //System.out.println(tmp);//默认排序结果:{1=壹, 2=贰, 3=三, 4=肆, 5=伍}         System.out.println(tmp);//修改为比较器排序(升序){5=伍, 4=肆, 3=三, 2=贰, 1=壹}     } //自定义TreeMap排序方法    比较器排序         class MyComparatorBigtoSmall implements Comparator<Integer>{         @Override         public int compare(Integer o1, Integer o2) {             // TODO Auto-generated method stub             return o2-o1;         }     }

如需了解两者的详细介绍,请点击https://blog.csdn.net/lichaohn/article/details/5389276

最后

以上就是俏皮路灯最近收集整理的关于Java中的自然排序和比较器排序的全部内容,更多相关Java中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部