对数组或数组列表排序
public class ArraySortDemo {
public static void main(String[] args) {
int[] nums = {100, 3, 4, 5, 2, 2, 1, 3, 7, 9, 9};
for (int num : nums) {
System.out.println("The number before sorting: " + num);
}
Arrays.sort(nums);
for (int num : nums) {
System.out.println("The number after sorting: " + num);
}
char[] chars = {'a', 'z', 'y', 'v', 'v', 'n', 'm', 'b', 'c', 'a'};
Arrays.sort(chars, 1, 5);
for (char ch : chars) {
System.out.println("The char after sorting: " + ch);
}
}
}
public class CollectionSortDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(50);
list.add(2);
list.add(3);
list.add(1);
list.add(7);
list.add(4);
list.add(26);
list.add(17);
for (int num : list){
System.out.println("The number before sorting: " + num);
}
Collections.sort(list);
for (int num : list){
System.out.println("The number after sorting: " + num);
}
List<Double> doubleList = new ArrayList<>();
doubleList.add(0.5);
doubleList.add(50.13);
doubleList.add(0.2);
doubleList.add(0.3);
doubleList.add(0.1);
doubleList.add(0.7);
doubleList.add(0.4);
doubleList.add(0.26);
doubleList.add(0.17);
for (double num : doubleList){
System.out.println("The double before sorting: " + num);
}
Collections.sort(doubleList);
for (double num : doubleList){
System.out.println("The double after sorting: " + num);
}
}
}
两个排序有关的重要接口
- Comparable 接口
- 位于 java.lang 包
- 让对象可以按照一定规则排序
- 核心方法:
public int compareTo(T o)
- 返回负数表示当前对象小于传入对象 o
- 返回正数表示当前对象大于传入对象 o
- 返回零表示当前对象等于传入对象 o
- Comparator 接口
- 位于 java.util 包
- 为啥有了 Comparable 接口还不够?
- 不是所有的类都会实现 Comparable 接口
- 即使实现 Comparable 接口,但排序规则也不是我们所希望的时候
- 核心方法:
int compare(T o1, T o2);
- 返回负数表示对象o1小于对象o2
- 返回正数表示对象o1大于对象o2
- 返回零表示对象o1等于对象o2