天天看点

java Collections.sort()方法

java.util.Collections.sort()是java.util.Collections类的方法。用来对指定列表的元素进行 升序 排列。它的工作方式类似于java.util.Arrays.sort()方法,但是它更好,因为它可以对Array的元素以及链表(linked list),队列(queue)等等进行排序。

ArrayList升序排列:

// Java program to demonstrate working of Collections.sort()
import java.util.*;

public class Collectionsorting
{
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> al = new ArrayList<String>();
        al.add("Geeks For Geeks");
        al.add("Friends");
        al.add("Dear");
        al.add("Is");
        al.add("Superb");

        /* Collections.sort method is sorting the
        elements of ArrayList in ascending order. */
        Collections.sort(al);

        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" + al);
    }
}
           

output:

List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
           

ArrayList降序排列:

// Java program to demonstrate working of Collections.sort()
// to descending order.
import java.util.*;

public class Collectionsorting
{
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> al = new ArrayList<String>();
        al.add("Geeks For Geeks");
        al.add("Friends");
        al.add("Dear");
        al.add("Is");
        al.add("Superb");

        /* Collections.sort method is sorting the
        elements of ArrayList in ascending order. */
        Collections.sort(al, Collections.reverseOrder());

        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" + al);
    }
}
           

output:

List after the use of Collection.sort() :
[Superb, Is, Geeks For Geeks, Friends, Dear]
           

ArrayList 按用户要求排列:

// Java program to demonstrate working of Comparator
// interface and Collections.sort() to sort according
// to user defined criteria.
import java.util.*;
import java.lang.*;
import java.io.*;

// A class to represent a student.
class Student
{
    int rollno;
    String name, address;

    // Constructor
    public Student(int rollno, String name,
                            String address)
    {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }

    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name +
                        " " + this.address;
    }
}

class Sortbyroll implements Comparator<Student>
{
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}

// Driver class
class Main
{
    public static void main (String[] args)
    {
        ArrayList<Student> ar = new ArrayList<Student>();
        ar.add(new Student(, "bbbb", "london"));
        ar.add(new Student(, "aaaa", "nyc"));
        ar.add(new Student(, "cccc", "jaipur"));

        System.out.println("Unsorted");
        for (int i=; i<ar.size(); i++)
            System.out.println(ar.get(i));

        Collections.sort(ar, new Sortbyroll());

        System.out.println("\nSorted by rollno");
        for (int i=; i<ar.size(); i++)
            System.out.println(ar.get(i));
    }
}
           

output:

Unsorted
 bbbb london
 aaaa nyc
 cccc jaipur

Sorted by rollno
 bbbb london
 cccc jaipur
 aaaa nyc
           

Arrays.sort() vs Collections.sort()

Arrays.sort()更多用于原始数据类型(primitive data type )

Collections.sort()更多用于objects Collections比如: ArrayList, LinkedList等等

// Using Collections.sort() to sort an array
import java.util.*;
public class Collectionsort
{
    public static void main(String[] args)
    {
        // create an array of string objs
        String domains[] = {"Practice", "Geeks",
                            "Code", "Quiz"};

        // Here we are making a list named as Collist
        List colList =
            new ArrayList(Arrays.asList(domains));

        // Collection.sort() method is used here
        // to sort the list elements.
        Collections.sort(colList);

        // Let us print the sorted list
        System.out.println("List after the use of" +
                        " Collection.sort() :\n" +
                        colList);
    }
}
           

ouput:

List after the use of Collection.sort()  :
[Code, Geeks, Practice, Quiz]
           

This article is contributed by Mohit Gupta

see more detail

Add:

Collection.sort()源码:

public static <T extends Comparable<? super T>> void sort(List<T> list) { Object[] a = list.toArray(); Arrays.sort(a); //注意这句 ListIterator<T> i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set((T)a[j]); } }

可以看到实际调用了Array类的sort()方法。再看Arrays.sort()源码:

public static void sort(Object[] a) {
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a);
        else
            ComparableTimSort.sort(a, , a.length, null, , );
    }