English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The sort() method of the collection framework uses the merge sort algorithm to sort the elements of the collection.
The merge sort algorithm is based on the divide and conquer rule. For more information about merge sort, please visit the merge sort algorithm page.
Let's take the sort() method as an example.
import java.util.ArrayList; import java.util.Collections; class Main { public static void main(String[] args) { // Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // Add elements numbers.add(4); numbers.add(2); numbers.add(3); System.out.println("Unsorted ArrayList: " + numbers); // Use sort() method Collections.sort(numbers); System.out.println("Sorted ArrayList: " + numbers); } }
Результат вывода
Неупорядоченный ArrayList: [4, 2, 3] Sorted ArrayList: [2, 3, 4]
As you can see, by default, sorting is performed in natural order (ascending). However, we can customize the sorting order of the sort() method.
In Java, you can customize the sort() method and perform sorting in reverse order using the Comparator interface.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class Main { public static void main(String[] args) { // Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // Add elements numbers.add(4); numbers.add(2); numbers.add(3); System.out.println("Unsorted ArrayList: " + numbers); // Use sort() method Collections.sort(numbers); System.out.println("Natural Sorting: " + numbers); // Use custom sort() method Collections.sort(numbers, new CustomComparator()); System.out.println("Customized Sorting: " + numbers); } } class CustomComparator implements Comparator<Integer> { @Override public int compare(Integer animal1, Integer animal2) { int value = animal1.compareTo(animal2); // элементы сортируются в обратном порядке if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } } }
Результат вывода
Неупорядоченный ArrayList: [4, 2, 3] Естественная сортировка: [2, 3, 4] Заказная сортировка: [4, 3, 2]
В примере выше мы использовали метод sort() и CustomComparator в качестве параметра.
Здесь CustomComparator - это класс, реализующий интерфейс Comparator. Узнайте больше о Java Comparator интерфейсе.
Затем перепишите метод compare(). Этот метод теперь будет сортировать элементы в обратном порядке.