深入理解Arrays.sort() (转)
Arrays.sort(T[], Comparator < ? super T > c) 方法用于对象数组按用户自定义规则排序.
官方Java文档只是简要描述此方法的作用,并未进行详细的介绍,本文将深入解析此方法。
1. 简单示例
sort方法的使用非常的简单明了,下面的例子中,先定义一个比较Dog大小的Comparator,然后将其实例对象作为参数传给sort方法,通过此示例,你应该能够快速掌握Arrays.sort()的使用方法。
- import java.util.Arrays;
- import java.util.Comparator;
- class Dog{
- int size;
- public Dog(int s){
- size = s;
- }
- }
- 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);
- Dog d2 = new Dog(1);
- Dog d3 = new Dog(3);
- 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(d.size + " " );
- System.out.println();
- }
- }
输出为:
- 2 1 3
- 1 2 3
2. 使用策略模式
这是策略模式(Strategy pattern)的一个完美又简洁的示例,值得一提的是为什么这种场景下适合使用策略模式.
总体来说,策略模式允许在程序执行时选择不同的算法.比如在排序时,传入不同的比较器(Comparator),就采用不同的算法.
根据上面的例子,假设你想要根据Dog的重量来进行排序,可以像下面这样,创建一个新的比较器来进行排序:
- class Dog{
- int size;
- int weight;
- public Dog(int s, int w){
- size = s;
- weight = w;
- }
- }
- class DogSizeComparator implements Comparator<Dog>{
- @Override
- public int compare(Dog o1, Dog o2) {
- return o1.size - o2.size;
- }
- }
- class DogWeightComparator implements Comparator<Dog>{
- @Override
- public int compare(Dog o1, Dog o2) {
- return o1.weight - o2.weight;
- }
- }
- 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);
- Arrays.sort(dogArray, new DogWeightComparator());
- printDogs(dogArray);
- }
- public static void printDogs(Dog[] dogs){
- for(Dog d: dogs)
- System.out.print("size="+d.size + " weight=" + d.weight + " ");
- System.out.println();
- }
- }
执行结果:
- size=2 weight=50 size=1 weight=30 size=3 weight=40
- size=1 weight=30 size=2 weight=50 size=3 weight=40
- size=1 weight=30 size=3 weight=40 size=2 weight=50
Comparator 是一个接口,所以sort方法中可以传入任意实现了此接口的类的实例,这就是策略模式的主要思想.
3. 为何使用"super"
如果使用 "Comparator < T > c" 那是很简单易懂的,但是sort的第2个参数里面的 < ? super T > 意味着比较器所接受的类型可以是T或者它的超类. 为什么是超类呢? 答案是: 这允许使用同一个比较器对不同的子类对象进行比较.在下面的示例中很明显地演示了这一点:
- import java.util.Arrays;
- import java.util.Comparator;
- class Animal{
- int size;
- }
- class Dog extends Animal{
- public Dog(int s){
- size = s;
- }
- }
- class Cat extends Animal{
- public Cat(int s){
- size = s;
- }
- }
- class AnimalSizeComparator implements Comparator<Animal>{
- @Override
- public int compare(Animal o1, Animal o2) {
- return o1.size - o2.size;
- }
- //in this way, all sub classes of Animal can use this comparator.
- }
- public class ArraySort {
- public static void main(String[] args) {
- Dog d1 = new Dog(2);
- Dog d2 = new Dog(1);
- Dog d3 = new Dog(3);
- Dog[] dogArray = {d1, d2, d3};
- printDogs(dogArray);
- Arrays.sort(dogArray, new AnimalSizeComparator());
- printDogs(dogArray);
- System.out.println();
- //when you have an array of Cat, same Comparator can be used.
- Cat c1 = new Cat(2);
- Cat c2 = new Cat(1);
- Cat c3 = new Cat(3);
- Cat[] catArray = {c1, c2, c3};
- printDogs(catArray);
- Arrays.sort(catArray, new AnimalSizeComparator());
- printDogs(catArray);
- }
- public static void printDogs(Animal[] animals){
- for(Animal a: animals)
- System.out.print("size="+a.size + " ");
- System.out.println();
- }
- }
输出结果:
- size=2 size=1 size=3
- size=1 size=2 size=3
- size=2 size=1 size=3
- size=1 size=2 size=3
4. 小结
与Arrays.sort()相关的信息总结如下:
- 通用: super 类
- 策略设计模式(strategy pattern);
- 归并排序(merge sort): 时间复杂度 n*log(n);
- Java.util.Collections#sort(List < T > list, Comparator < ? super T > c)与Arrays.sort 使用类似的思想.
http://blog.csdn.net/wisgood/article/details/16541013
深入理解Arrays.sort() (转)的更多相关文章
- 深入理解Arrays.sort()
两种方法: 1.类本来就实现java.lang.Comparable接口,使类本身就有比较能力.接口实现compareTo方法,次方法接收另一个Object为参数,如果当前对象小于参数则返回负值,如果 ...
- [转]Arrays.sort()你应该知道的事
以下内容转自: 原文链接: programcreek 翻译: ImportNew.com- 刘志军 译文链接: http://www.importnew.com/8952.html --------- ...
- Arrays.sort源代码解析
Java Arrays.sort源代码解析 Java Arrays中提供了对所有类型的排序.其中主要分为Primitive(8种基本类型)和Object两大类. 基本类型:采用调优的快速排序: 对象类 ...
- Arrays.sort解析
Arrays.sort()解读 在学习了排序算法之后, 再来看看 Java 源码中的, Arrays.sort() 方法对于排序的实现. 都是对基本数据类型的排序实现, 下面来看看这段代码: Arra ...
- Java 容器 & 泛型:四、Colletions.sort 和 Arrays.sort 的算法
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket 本来准备讲 Map集合 ,还是喜欢学到哪里总结吧.最近面试期准备准备,我是一员,成功被阿里在线笔试秒杀 ...
- Java Arrays.sort源代码解析
前提: 当用到scala的sortWith,发现: def sortWith(lt: (A, A) ⇒ Boolean): List[A] // A为列表元素类型 根据指定比较函数lt进行排序,且排序 ...
- Arrays.sort()的底层实现
1.基本类型(以int为例) 源码中的快速排序,主要做了以下几个方面的优化: 1)当待排序的数组中的元素个数较少时,源码中的阀值为7,采用的是插入排序.尽管插入排序的时间复杂度为0(n^2),但是当数 ...
- 5.4 集合的排序(Java学习笔记)(Collections.sort(),及Arrays.sort()底层分析)
1.Comparable接口 这个接口顾名思义就是用于排序的,如果要对某些对象进行排序,那么该对象所在的类必须实现 Comparabld接口.Comparable接口只有一个方法CompareTo() ...
- Java Arrays.sort相关用法与重载
Java Arrays.sort() Java中的数组排序函数, 头文件 import java.util.Arrays; 相关API Arrays.sort(arys[]) Arrays.sort( ...
随机推荐
- 整数运算:CPU内部只有加法运算
学汇编的一边儿去.我这里讲的是CPU进行计算的原理.首先我这里用MC的红石电路模拟了一个加法器:http://www.0xaa55.com/thread-313-1-1.htm首先加法器是怎么实现的呢 ...
- 数论(容斥原理)hdu-4509-The Boss on Mars
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=4059 题目大意: 给一个n,求1~n中与n互质的数的4次方的总和. 解题思路: 容斥原理.逆元.公式 ...
- 完整的yuicompressor单个压缩和批量压缩以及gzip再次压缩,拦截器的配置等
下载地址:http://yuilibrary.com/download/yuicompressor/ 个人认为现在yuicompressor是最安全,最值得信赖的压缩工具,至少到现在没出现过问题 1. ...
- Android 文件共享服务器
http://download.csdn.net/detail/liduanw/6271075 你可以将自己的手机作为(局域网)服务器, 使用方法: 1> 指定共享根目录 2> 点击启动 ...
- Swift - 表格图片加载优化(拖动表格时不加载,停止时只加载当前页图片)
列表的单元格中包含有图片在开发中很常见.通常我们可以直接在tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIn ...
- 数据交换工具Kettle
网上搜集了一些关于开源数据交换工具Kattle的文章,特收藏例如以下: 文章一:ETL和Kettle简单介绍 ETL即数据抽取(Extract).转换(Transform).装载(Load)的过程.它 ...
- 微信jsSDK开发
(学习类)2015年最新微信公众平台开发 微信JSSDK开发分享功能 链接地址:http://blog.163.com/sdolove@126/blog/static/1146378852015132 ...
- OCP-1Z0-042-V12.39-51题
51.Which two statements regarding archive log destinations are true? 题目解析: A(正确)因为:.归档日志最多可以配置10个 B和 ...
- .net版Git Server --- bonobo
官网地址: https://bonobogitserver.com/ Demo: http://demo.bonobogitserver.com/Home/LogOn 登入admin:admin C ...
- 通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)-大壮他哥
步骤: 1.运行--〉cmd:打开cmd命令框 2.在命令行里定位到InstallUtil.exe所在的位置 InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft ...