常用的比较器:实现方式Compareable和Comparator
2017-10-15 10:58
483 查看
class Dog{ int size; int weight; public Dog(int s, int w){ size = s; weight = w; } }
目的:对于Dog对象作为元素所组成的数组进行对象属性的自定义排序
一、外部比较器 Comparator:优点是不对源代码造成影响
class DogSizeComparator implements Comparator<Dog>{ @Override public int compare(Dog o1, Dog o2) { return o1.size - o2.size; } } public class ArraySort { public static void main(String[] args) { Dog d1 = new Dog(2, 50); Dog d2 = new Dog(1, 30); Dog d3 = new Dog(3, 40); Dog[] dogArray = {d1, d2, d3}; printDogs(dogArray); Arrays.sort(dogArray, new DogSizeComparator()); printDogs(dogArray); } public static void printDogs(Dog[] dogs){ for(Dog d: dogs) System.out.print("size="+d.size + " weight=" + d.weight + " "); System.out.println(); } }
1、编写一个外部比较器:实现Comparator泛型为需要排序对象的类,并重写
compare(Dog o1, Dog o2)方法,如果进行正序的排序,那返回值为o1.属性-o2.属性,属性为根据此排序的参考
2、通过Arrays.sort(dogArray, new DogSizeComparator());参数为需要排序的对象的数组和对应比较器,进行排序
二、内部比较器Compareable:对象所属的类需要实现Compareable接口
public class Person implements Comparable<Person> { String name; int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public int compareTo(Person p) { return this.age-p.getAge(); } public static void main(String[] args) { Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)}; System.out.println("排序前"); for (Person person : people) { System.out.print(person.getName()+":"+person.getAge()); } Arrays.sort(people); System.out.println("\n排序后"); for (Person person : people) { System.out.print(person.getName()+":"+person.getAge()); } } }
1所需要排序数组的元素对象所属的类 必须要实现Compareable接口并重写 compareTo()方法 正序返回this.属性-参数对象.属性 反序则取反。
2对于该对象的数组使用Arrays.sort(people)进行排序
相关文章推荐
- java常用加密方式实现
- Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式
- Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式
- JavaScript实现创建自定义对象的常用方式总结
- 9种网页动画常用实现方式总结
- Windows平台下常用进程间通信的实现方式
- Java Singletom 单例模式 常用实现方式
- 列举常用排序算法以及实现方式
- HTML页面-------3秒之后自动跳转的3种常用的实现方式
- TextView实现带链接文字事件监听三种常用方式
- 现在常用的单例模式实现方式
- 系统幂等以及常用实现方式
- 关于wordpress侧边栏常用功能的非插件方式实现
- Windows平台下常用进程间通信的实现方式
- Spring AOP 常用的四种实现方式
- iOS- 网络访问两种常用方式【GET & POST】实现的几个主要步骤
- TreeSet集合排序两种实现方式Comparable和Comparator比较
- 启动就加载(一)----注解方式实现的。static项目启动的时候就加载进来(一般用于常用参数)
- Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式