Java自定义排序

来源:互联网 发布:蓝光 刻录 数据 编辑:程序博客网 时间:2024/06/15 22:45

本文主要介绍Java常用的排序方法:Arrays.sort()、Collections.sort()

这两种方法的使用方法基本相同,不同的是Collections.sort()只能对对象容器排序,而Arrays.sort()只能对数组进行排序,数组可以是基本类型数组和对象数组。下面用Collection.sort()举例,Arrays.sort()类似。


Collections.sort()有如下两种形式:


1.  public static <T extendsComparable<?super T>> void sort(List<T> list)

sort对容器直接排序的前提是该容器的元素要实现Comparable接口,对于常用的基本类型的包装类型如Integer、Long等类和String类都已经实现了Comparable,所以可以直接用Collections.sort(list)进行排序。要实现Comparable接口只需要实现compare()方法(因为Comparable只有一个方法)。如果容器的对象并没有实现Comparable接口或者已经实现了但是要按照自定义方法进行排序,这里就要用到Collections.sort()的另一种形式,如下。

 

2.  public static <T> void sort(List<T>list, Comparator<? super T> c)

此方法可以实现自定义排序,而且比一种方法灵活,只要指定相应的比较器可以灵活使用多种排序机制。使用方法如下:

MyComparator c =new MyComparator();

Collections.sort(list,c);

其中MyComparator必须实现Comparator接口

示例:

import java.util.*;public class MyCompatorDemo {    public static void main(String[] args) {        List<MyClass> list1 = new ArrayList<MyClass>();        list1.add(new MyClass("a", 1));        list1.add(new MyClass("b", 2));        list1.add(new MyClass("c", 3));        list1.add(new MyClass("d", 4));        list1.add(new MyClass("e", 5));        //按照MyClass内部的compareTo方法进行排序        Collections.sort(list1);        //输出        for(MyClass myClass : list1){            System.out.println(myClass.name + " " + myClass.id);        }        //初始化序列        List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5, 3);        //使用默认排序方式(升序)        Collections.sort(list2);        System.out.println(list2);        //使用自定义排序方式(降序)        MyComparator c = new MyComparator();        Collections.sort(list2, c);        System.out.println(list2);    }}class MyClass implements Comparable{    String name = "";    int id = 0;    MyClass(){    }    MyClass(String name, int id){        this.name = name;        this.id = id;    }    @Override    public int compareTo(Object o) {        MyClass myClass = (MyClass) o;        return 0 - this.name.compareTo(myClass.name);    }}//实现Comparator的类class MyComparator implements Comparator<Integer> {    @Override    public int compare(Integer a, Integer b){        return b - a;    }}

程序运行结果:

e 5
d 4
c 3
b 2
a 1
[1, 2, 3, 3, 4, 5]
[5, 4, 3, 3, 2, 1]

注意:

  • Collections.sort()和Arrays.sort()都是稳定的排序方法。
  • Arrays.sort()和Collections.sort()使用形式类似,就是序列对象不一,一个对容器,一个对数组

原创粉丝点击