集合类sort()方法 (Collections Class sort() method)
Syntax:
句法:
public static void sort(List l);
public static void sort(List l, Comparator com);
sort() method is available in java.util package.
在java.util包中可以使用sort()方法 。
sort(List l) method is used to sort the given list according to natural sorting (i.e. sorting will be in ascending order).
sort(List l)方法用于根据自然排序对给定列表进行排序(即排序将以升序排列)。
sort(List l, Comparator com) method is used to sort the given list according to customized sorting (i.e. sorting will be based on the given Comparator com).
sort(List l,Comparator com)方法用于根据自定义排序对给定列表进行排序(即,排序将基于给定的Comparator com)。
These methods may throw an exception at the time of sorting the given list.
这些方法在对给定列表进行排序时可能会引发异常。
- ClassCastException: This exception may throw when the given list elements are mutually incomparable.ClassCastException :当给定列表元素相互不可比较时,可能会引发此异常。
- UnsupportedOperationException: This exception may throw when the given list un-support set operation.UnsupportedOperationException :当给定列表不支持set操作时,可能引发此异常。
These are static methods and it is accessible with the class name and if we try to access these methods with the class object then also we will not get any error.
这些是静态方法,可以使用类名进行访问,如果尝试使用类对象访问这些方法,则也不会出现任何错误。
Parameter(s):
参数:
In the first case, sort(List l),
在第一种情况下, sort(List l) ,
- List l – represents the list that is for sorting.
- 列表l –表示要排序的列表。
In the first case, sort(List l, Comparator com),
在第一种情况下, sort(List l,Comparator com) ,
- List l – represents the list that is for sorting.
- 列表l –表示要排序的列表。
- Comparator com – represents the Comparator with which to calculate the order (ascending or descending) of the given list.
- 比较器com –表示比较器,用来计算给定列表的顺序(升序或降序)。
Return value:
返回值:
In both the cases, the return type of the method is void, it does not return anything.
在这两种情况下,方法的返回类型均为void ,它不返回任何内容。
Example:
例:
// Java program to demonstrate the example
// of sort() method of Collections
import java.util.*;
public class SortOfCollections {
public static void main(String args[]) {
// Instantiates an ArrayList
ArrayList arr_l = new ArrayList();
// By using add() method is to add
// objects in an array list
arr_l.add(20);
arr_l.add(10);
arr_l.add(50);
arr_l.add(40);
arr_l.add(80);
// Display ArrayList
System.out.println("arr_l : " + arr_l);
// By using sort(arr_l,Comparator) method is
// to sort the arraylist by using comparator object
Collections.sort(arr_l, null);
// Display ArrayList
System.out.println("Collections.sort(arr_l, null): " + arr_l);
// By using sort(arr_l) method is
// to sort the arraylist without using
// comparator object
Collections.sort(arr_l);
//Display ArrayList
System.out.println("Collections.sort(arr_l): " + arr_l);
}
}
Output
输出量
arr_l : [20, 10, 50, 40, 80]
Collections.sort(arr_l, null): [10, 20, 40, 50, 80]
Collections.sort(arr_l): [10, 20, 40, 50, 80]
翻译自: https://www.includehelp.com/java/collections-sort-method-with-example.aspx