Are you sure you're getting this? Fill in the missing part by typing it in.
The Collections
class provides many utility methods for working with collections in Java. One such method is the _____________()
method, which is used to sort the elements in a list in natural order or using a custom comparator.
The Collections.sort()
method takes a list as input and rearranges its elements in ascending order. If the list contains elements of a class that implements the Comparable
interface, the elements are sorted based on their natural order. If the list contains elements of a class that does not implement the Comparable
interface, a custom comparator can be provided to determine the sorting order.
The following code demonstrates the usage of the Collections.sort()
method:
1import java.util.ArrayList;
2import java.util.Collections;
3
4public class Main {
5 public static void main(String[] args) {
6 // Create an ArrayList
7 ArrayList<Integer> numbers = new ArrayList<>();
8
9 // Add elements to the ArrayList
10 numbers.add(5);
11 numbers.add(2);
12 numbers.add(8);
13 numbers.add(1);
14
15 System.out.println("Original ArrayList: " + numbers);
16
17 // Use the Collections class to sort the ArrayList
18 Collections.sort(numbers);
19
20 System.out.println("Sorted ArrayList: " + numbers);
21 }
22}
In the above code, we create an ArrayList
of integers and add some elements to it. We then use the Collections.sort()
method to sort the elements in the ArrayList
in ascending order. Finally, we print the sorted ArrayList
to the console.
Write the missing line below.