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 the opposite 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.
ثم أعيد كتابة مقارنة() في هذا السياق. الآن سينظم هذا الطريقة العكسية للعناصر.