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

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

[java] view plaincopy

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

输出为:

[plain] view plaincopy

  1. 2 1 3
  2. 1 2 3

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

[java] view plaincopy

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

执行结果:

[plain] view plaincopy

  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 plaincopy

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

输出结果:

[plain] view plaincopy

  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

时间: 2024-07-29 02:06:07

深入理解Arrays.sort() (转)的相关文章

(转)Arrays.sort()你应该知道的事

Arrays.sort(T[], Comparator < ? super T > c) 是用来对用户自定义的对象数组排序功能的.Java 官方文档简单描述了它的作用,但不足以让我们深刻理解.为了更深入地理解它,这篇文章将梳理相关的关键点. 1.简单实例:如何使用Arrays.sort() 通过阅读下面代码,你能快速正确了解这个方法的用途.Comparator(比较器)用于根据Dogs的size比较其大小,并作为sort方法的参数. 1 2 3 4 5 6 7 8 9 10 11 12 13

Java 容器 &amp; 泛型:四、Colletions.sort 和 Arrays.sort 的算法

Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket 本来准备讲 Map集合 ,还是喜欢学到哪里总结吧.最近面试期准备准备,我是一员,成功被阿里在线笔试秒杀回绝.平常心,继续努力.这次带来 Collections 和 Arrays 类中的经典算法剖析. 一.Colletions和Arrays Collentions 此类完全是服务容器的”包装器“.提供了一些操作或者返回容器的静态方法.而Arrays是用来操作数组的各种方法.其中它们的联系在于其中的So

(转载)Java 容器 &amp; 泛型:四、Colletions.sort 和 Arrays.sort 的算法

讲 Map集合 ,还是喜欢学到哪里总结吧.最近面试期准备准备,我是一员,成功被阿里在线笔试秒杀回绝.平常心,继续努力.这次带来 Collections 和 Arrays 类中的经典算法剖析. 一.Colletions和Arrays Collentions 此类完全是服务容器的”包装器“.提供了一些操作或者返回容器的静态方法.而Arrays是用来操作数组的各种方法.其中它们的联系在于其中的Sort方法,也就是这次博客的主题. 二.插入,快速.归并基本算法 ① 插入排序 {a1},{a2,a3,a4

Arrays.sort解析

Arrays.sort()解读 在学习了排序算法之后, 再来看看 Java 源码中的, Arrays.sort() 方法对于排序的实现. 都是对基本数据类型的排序实现, 下面来看看这段代码: Arrays.sort(int[] a) public static void sort(int[] a) { DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0); } DualPivotQuicksort.sort 在这里我将代码一步步拆开来看,

JAVA中Arrays.sort()使用两种方式(Comparable和Comparator接口)对对象或者引用进行排序

一.描述 自定义的类要按照一定的方式进行排序,比如一个Person类要按照年龄进行从小到大排序,比如一个Student类要按照成绩进行由高到低排序. 这里我们采用两种方式,一种是使用Comparable接口:让待排序对象所在的类实现Comparable接口,并重写Comparable接口中的compareTo()方法,缺点是只能按照一种规则排序. 另一种方式是使用Comparator接口:编写多个排序方式类实现Comparator接口,并重写新Comparator接口中的compare()方法,

关于使用Java中Arrays.sort()方法TLE

最近一直在练用Java写题(链接),今天无意发现一道很简单的二分题,我一开始是直接开int[]数组调用Arrays.sort()去排序,没想到TLE了,原来是因为jdk中对于int[]的排序是使用快速排序的,jdk中相关调用源码如下 1 public static void sort(int[] a) { 2 DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0); 3 } 而测试数据恰好有反快排的数据,因此被卡. 解决方法也不少,比较简单

JAVA数组与排序(Arrays.sort(数组名))

import java.util.Scanner; import java.util.Arrays; public class ArrayTest03 { public static void main(String[] args) { System.out.println("请输入数组的长度:"); InPut in = new InPut();                                      //调用类InPut int n =in.in_put();  

java中一句话实现排序Arrays.sort(数组名);

import java.util.*; public class Main { public static void main(String[] args){ Scanner in =new Scanner(System.in); int n; n=in.nextInt(); int s[]=new int[n]; for(int i=0;i<n;i++){ s[i]=in.nextInt(); } Arrays.sort(s); for(int i=0; i<n; i++) System.o

SDUT 1591-交叉排序(Arrays.sort)

交叉排序 Time Limit: 1000ms   Memory limit: 32768K  有疑问?点这里^_^ 题目描述 输入N个数,把所有奇数位置上的数从小到大排序,把偶数位置上的数从大到小排序. 输入 输入的第一行是一个正整数N(2<=N<=100). 第二行是N个用空格隔开的整数. 输出 输出只有一行N个数,是按要求排序后的序列,用空格隔开. 示例输入 6 1 2 3 4 5 6 示例输出 1 6 3 4 5 2 java的Arrays类居然只有升序排序..sad import j