排序数组
import java.util.Arrays;
// creating an array with integers
int[] array = {7, 4, 2, 1, 19};
// this is the sorting part just one function ready to be used
Arrays.sort(array);
// prints [1, 2, 4, 7, 19]
System.out.println(Arrays.toString(array));
排序字符串数组:
String
不是数字数据,它定义了它自己的顺序,称为词典顺序,也称为字母顺序。使用 sort()
方法对 String 数组进行排序时,它会将数组排序为 Comparable 接口定义的自然顺序,如下所示:
增加订单
String[] names = {"John", "Steve", "Shane", "Adam", "Ben"};
System.out.println("String array before sorting : " + Arrays.toString(names));
Arrays.sort(names);
System.out.println("String array after sorting in ascending order : " + Arrays.toString(names));
输出:
String array before sorting : [John, Steve, Shane, Adam, Ben]
String array after sorting in ascending order : [Adam, Ben, John, Shane, Steve]
减少订单
Arrays.sort(names, 0, names.length, Collections.reverseOrder());
System.out.println("String array after sorting in descending order : " + Arrays.toString(names));
输出:
String array after sorting in descending order : [Steve, Shane, John, Ben, Adam]
对 Object 数组进行排序
为了对对象数组进行排序,所有元素都必须实现 Comparable
或 Comparator
接口来定义排序顺序。
我们可以使用 sort(Object[])
方法按自然顺序对对象数组进行排序,但是必须确保数组中的所有元素都必须实现 Comparable
。
此外,它们也必须是相互可比的,例如 e1.compareTo(e2)
不能为数组中的任何元素 e1 和 e2 抛出 ClassCastException
。或者,你可以使用 sort(T[], Comparator)
方法对自定义顺序的 Object 数组进行排序,如以下示例所示。
// How to Sort Object Array in Java using Comparator and Comparable
Course[] courses = new Course[4];
courses[0] = new Course(101, "Java", 200);
courses[1] = new Course(201, "Ruby", 300);
courses[2] = new Course(301, "Python", 400);
courses[3] = new Course(401, "Scala", 500);
System.out.println("Object array before sorting : " + Arrays.toString(courses));
Arrays.sort(courses);
System.out.println("Object array after sorting in natural order : " + Arrays.toString(courses));
Arrays.sort(courses, new Course.PriceComparator());
System.out.println("Object array after sorting by price : " + Arrays.toString(courses));
Arrays.sort(courses, new Course.NameComparator());
System.out.println("Object array after sorting by name : " + Arrays.toString(courses));
输出:
Object array before sorting : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]
Object array after sorting in natural order : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]
Object array after sorting by price : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]
Object array after sorting by name : [#101 Java@200 , #301 Python@400 , #201 Ruby@300 , #401 Scala@500 ]