javable之Comparable
Posted 暮雨煙深淺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javable之Comparable相关的知识,希望对你有一定的参考价值。
我们知道,在Java的集合类中是有一些可复用的算法的,比如
Collections.sort()从小到大排序,Collections.min(),最小值Collections.max()最大值,
这些对于list操作来说都是非常常见的,也经常需要用到
List<String> strings = new ArrayList<String>(); strings.add("ab"); strings.add("cc"); strings.add("bc"); Collections.sort(strings); String max =Collections.max(strings); String min =Collections.min(strings); System.out.println(strings);//[ab, bc, cc] System.out.println(max);//cc System.out.println(min);//ab List<Integer> integers = new ArrayList<Integer>(); integers.add(2); integers.add(1); integers.add(3); Collections.sort(integers); Integer max1 =Collections.max(integers); Integer min1 =Collections.min(integers); System.out.println(integers);//[1, 2, 3] System.out.println(max1);//3 System.out.println(min1);//1
那么问题就来了,例子中的String,Integer,都是可比较的元素,如果是自定义的ADT怎么办呢?或者是如何按照我们想的比大小的方式,比如这里String是字典序,Integer是升序,我想要换一种方式,怎么办呢?
这里有两种方法
1实现Comparable 排序接口,并实现public int compareTo(Object o)方法
public class UseAnimals { public static void main(String[] args) { List<Dog> dogs = new ArrayList<Dog>(); Dog dog1 = new Dog(1,"Mary"); Dog dog2 = new Dog(3,"Elizabeth"); Dog dog3 = new Dog(2,"Anne Boleyn"); dogs.add(dog1); dogs.add(dog2); dogs.add(dog3); Collections.sort(dogs); Dog max =Collections.max(dogs); Dog min =Collections.min(dogs); System.out.println(dogs);//[Mary 1, Anne Boleyn 2, Elizabeth 3] System.out.println(max);//Elizabeth 3 System.out.println(min);//Mary 1 } } class Dog implements Comparable<Dog> { int age; String name ; public Dog (int age,String name) { this.age=age; this.name=name; } @Override public int compareTo(Dog o) { // TODO Auto-generated method stub return (this.age>o.age)? 1:-1; } @Override public String toString() { // TODO Auto-generated method stub return name+" "+age; } }
2.通过传入参数比较器Comparator来实现
public static void main(String[] args) { List<Dog> dogs = new ArrayList<Dog>(); Dog dog1 = new Dog(1,"Mary"); Dog dog2 = new Dog(3,"Elizabeth"); Dog dog3 = new Dog(2,"Anne Boleyn"); dogs.add(dog1); dogs.add(dog2); dogs.add(dog3); Comparator<Dog> cia = new Comparator<Dog>(){ @Override public int compare(Dog o1, Dog o2) { return o1.age - o2.age; } }; Collections.sort(dogs,cia); Dog max =Collections.max(dogs); Dog min =Collections.min(dogs); System.out.println(dogs);//[Mary 1, Anne Boleyn 2, Elizabeth 3] System.out.println(max);//Elizabeth 3 System.out.println(min);//Mary 1 }
当然也可以简单写成:
Collections.sort(dogs, new Comparator<Dog>() { @Override public int compare(Dog o1, Dog o2) { return o1.age - o2.age; } });
这样就可以实现对自定义的ADT以自己想要的方式排序或者一键最大最小值了。
以上是关于javable之Comparable的主要内容,如果未能解决你的问题,请参考以下文章
Java:Effective java学习笔记之 考虑实现Comparable 接口
Collection集合之六大接口(CollectionSetListMapIterator和Comparable)