深入理解Arrays.sort() (转)

简介: Arrays.sort(T[], Comparator < ? super T > c) 方法用于对象数组按用户自定义规则排序.官方Java文档只是简要描述此方法的作用,并未进行详细的介绍,本文将深入解析此方法。

Arrays.sort(T[], Comparator < ? super T > c) 方法用于对象数组按用户自定义规则排序.
官方Java文档只是简要描述此方法的作用,并未进行详细的介绍,本文将深入解析此方法。
1. 简单示例
sort方法的使用非常的简单明了,下面的例子中,先定义一个比较Dog大小的Comparator,然后将其实例对象作为参数传给sort方法,通过此示例,你应该能够快速掌握Arrays.sort()的使用方法。

[java]  view plain copy
 
 
  1. import java.util.Arrays;  
  2. import java.util.Comparator;  
  3.    
  4. class Dog{  
  5.     int size;     
  6.     public Dog(int s){  
  7.         size = s;  
  8.     }  
  9. }  
  10.    
  11. class DogSizeComparator implements Comparator<Dog>{  
  12.    
  13.     @Override  
  14.     public int compare(Dog o1, Dog o2) {  
  15.         return o1.size - o2.size;  
  16.     }  
  17. }  
  18.    
  19. public class ArraySort {  
  20.    
  21.     public static void main(String[] args) {  
  22.         Dog d1 = new Dog(2);  
  23.         Dog d2 = new Dog(1);  
  24.         Dog d3 = new Dog(3);  
  25.    
  26.         Dog[] dogArray = {d1, d2, d3};  
  27.         printDogs(dogArray);  
  28.    
  29.         Arrays.sort(dogArray, new DogSizeComparator());   
  30.         printDogs(dogArray);  
  31.     }  
  32.    
  33.     public static void printDogs(Dog[] dogs){  
  34.         for(Dog d: dogs)  
  35.             System.out.print(d.size + " " );  
  36.    
  37.         System.out.println();  
  38.     }  
  39. }  

输出为:

[plain]  view plain copy
 
 
  1. 2 1 3  
  2. 1 2 3  


2. 使用策略模式
这是策略模式(Strategy pattern)的一个完美又简洁的示例,值得一提的是为什么这种场景下适合使用策略模式.
总体来说,策略模式允许在程序执行时选择不同的算法.比如在排序时,传入不同的比较器(Comparator),就采用不同的算法.
根据上面的例子,假设你想要根据Dog的重量来进行排序,可以像下面这样,创建一个新的比较器来进行排序:

[java]  view plain copy
 
 
  1. class Dog{  
  2.     int size;  
  3.     int weight;  
  4.    
  5.     public Dog(int s, int w){  
  6.         size = s;  
  7.         weight = w;   
  8.     }  
  9. }  
  10.    
  11. class DogSizeComparator implements Comparator<Dog>{  
  12.    
  13.     @Override  
  14.     public int compare(Dog o1, Dog o2) {  
  15.         return o1.size - o2.size;  
  16.     }  
  17. }  
  18.    
  19. class DogWeightComparator implements Comparator<Dog>{  
  20.    
  21.     @Override  
  22.     public int compare(Dog o1, Dog o2) {  
  23.         return o1.weight - o2.weight;  
  24.     }  
  25. }  
  26.    
  27. public class ArraySort {  
  28.    
  29.     public static void main(String[] args) {  
  30.         Dog d1 = new Dog(2, 50);  
  31.         Dog d2 = new Dog(1, 30);  
  32.         Dog d3 = new Dog(3, 40);  
  33.    
  34.         Dog[] dogArray = {d1, d2, d3};  
  35.         printDogs(dogArray);  
  36.    
  37.         Arrays.sort(dogArray, new DogSizeComparator());   
  38.         printDogs(dogArray);  
  39.    
  40.         Arrays.sort(dogArray, new DogWeightComparator());     
  41.         printDogs(dogArray);  
  42.     }  
  43.    
  44.     public static void printDogs(Dog[] dogs){  
  45.         for(Dog d: dogs)  
  46.             System.out.print("size="+d.size + " weight=" + d.weight + " ");  
  47.    
  48.         System.out.println();  
  49.     }  
  50. }  

执行结果:

[plain]  view plain copy
 
 
  1. size=2 weight=50 size=1 weight=30 size=3 weight=40  
  2. size=1 weight=30 size=2 weight=50 size=3 weight=40  
  3. size=1 weight=30 size=3 weight=40 size=2 weight=50  

Comparator 是一个接口,所以sort方法中可以传入任意实现了此接口的类的实例,这就是策略模式的主要思想.

3. 为何使用"super"
如果使用 "Comparator < T > c" 那是很简单易懂的,但是sort的第2个参数里面的 < ? super T > 意味着比较器所接受的类型可以是T或者它的超类. 为什么是超类呢? 答案是: 这允许使用同一个比较器对不同的子类对象进行比较.在下面的示例中很明显地演示了这一点:

[java]  view plain copy
 
 
  1. import java.util.Arrays;  
  2. import java.util.Comparator;  
  3.    
  4. class Animal{  
  5.     int size;  
  6. }  
  7.    
  8. class Dog extends Animal{  
  9.     public Dog(int s){  
  10.         size = s;  
  11.     }  
  12. }  
  13.    
  14. class Cat extends Animal{  
  15.     public Cat(int s){  
  16.         size  = s;  
  17.     }  
  18. }  
  19.    
  20. class AnimalSizeComparator implements Comparator<Animal>{  
  21.    
  22.     @Override  
  23.     public int compare(Animal o1, Animal o2) {  
  24.         return o1.size - o2.size;  
  25.     }  
  26.     //in this way, all sub classes of Animal can use this comparator.  
  27. }  
  28.    
  29. public class ArraySort {  
  30.    
  31.     public static void main(String[] args) {  
  32.         Dog d1 = new Dog(2);  
  33.         Dog d2 = new Dog(1);  
  34.         Dog d3 = new Dog(3);  
  35.    
  36.         Dog[] dogArray = {d1, d2, d3};  
  37.         printDogs(dogArray);  
  38.    
  39.         Arrays.sort(dogArray, new AnimalSizeComparator());    
  40.         printDogs(dogArray);  
  41.    
  42.         System.out.println();  
  43.    
  44.         //when you have an array of Cat, same Comparator can be used.   
  45.         Cat c1 = new Cat(2);  
  46.         Cat c2 = new Cat(1);  
  47.         Cat c3 = new Cat(3);  
  48.    
  49.         Cat[] catArray = {c1, c2, c3};  
  50.         printDogs(catArray);  
  51.    
  52.         Arrays.sort(catArray, new AnimalSizeComparator());    
  53.         printDogs(catArray);  
  54.     }  
  55.    
  56.     public static void printDogs(Animal[] animals){  
  57.         for(Animal a: animals)  
  58.             System.out.print("size="+a.size + " ");  
  59.    
  60.         System.out.println();  
  61.     }  
  62. }  

输出结果:

[plain]  view plain copy
 
 
  1. size=2 size=1 size=3  
  2. size=1 size=2 size=3  
  3. size=2 size=1 size=3  
  4. size=1 size=2 size=3  


4. 小结
与Arrays.sort()相关的信息总结如下:

    1. 通用: super 类
    2. 策略设计模式(strategy pattern);
    3. 归并排序(merge sort): 时间复杂度 n*log(n);
    4. Java.util.Collections#sort(List < T > list, Comparator < ? super T > c)与Arrays.sort 使用类似的思想.


http://blog.csdn.net/wisgood/article/details/16541013

相关文章
|
存储 Kubernetes 网络协议
K8S常见问题
【10月更文挑战第2天】
646 4
Context Root选/的原则
Context Root通常是/. 这个代表了你的web module的名字。当只有一个web module的时候,是可以将应用程序部署到/的。也就是说部分可以是长度为零的空串。那个整个Context Root就成了/. 通常只为你的主站做如此部署。
670 0
|
2天前
|
存储 弹性计算 人工智能
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
2025年9月24日,阿里云弹性计算团队多位产品、技术专家及服务器团队技术专家共同在【2025云栖大会】现场带来了《通用计算产品发布与行业实践》的专场论坛,本论坛聚焦弹性计算多款通用算力产品发布。同时,ECS云服务器安全能力、资源售卖模式、计算AI助手等用户体验关键环节也宣布升级,让用云更简单、更智能。海尔三翼鸟云服务负责人刘建锋先生作为特邀嘉宾,莅临现场分享了关于阿里云ECS g9i推动AIoT平台的场景落地实践。
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
|
3天前
|
云安全 数据采集 人工智能
古茗联名引爆全网,阿里云三层防护助力对抗黑产
阿里云三层校验+风险识别,为古茗每一杯奶茶保驾护航!
古茗联名引爆全网,阿里云三层防护助力对抗黑产
|
4天前
|
存储 机器学习/深度学习 人工智能
大模型微调技术:LoRA原理与实践
本文深入解析大语言模型微调中的关键技术——低秩自适应(LoRA)。通过分析全参数微调的计算瓶颈,详细阐述LoRA的数学原理、实现机制和优势特点。文章包含完整的PyTorch实现代码、性能对比实验以及实际应用场景,为开发者提供高效微调大模型的实践指南。
514 1
kde
|
4天前
|
人工智能 关系型数据库 PostgreSQL
n8n Docker 部署手册
n8n是一款开源工作流自动化平台,支持低代码与可编程模式,集成400+服务节点,原生支持AI与API连接,可自托管部署,助力团队构建安全高效的自动化流程。
kde
347 3
|
2天前
|
Linux 虚拟化 iOS开发
VMware Workstation Pro 25H2 for Windows & Linux - 领先的免费桌面虚拟化软件
VMware Workstation Pro 25H2 for Windows & Linux - 领先的免费桌面虚拟化软件
681 4
VMware Workstation Pro 25H2 for Windows & Linux - 领先的免费桌面虚拟化软件