WalzoneInterview Prep
๐Ÿ“ž Interviewing soon? Practice with a realistic AI mock phone interview โ€” it calls you, then scores you. First 15 min FREE โ†’

Java Collections ยท Expert ยท question 69 of 100

How does the Collections.sort() method work in Java Collections, and what is its time complexity?

๐Ÿ“• Buy this interview preparation book: 100 Java Collections questions & answers โ€” PDF + EPUB for $5

The Collections.sort() method is used to sort the elements of a list in ascending order. It is a static method of the java.util.Collections class and takes a single argument, which is the list to be sorted.

The Collections.sort() method internally uses the merge sort algorithm, which has a time complexity of O(n log n) in the worst case scenario. The merge sort algorithm is a divide-and-conquer algorithm that divides the list into sublists, sorts each sublist, and then merges the sorted sublists back together.

Here is an example Java code that demonstrates the use of the Collections.sort() method:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(8);
        numbers.add(1);
        numbers.add(10);
        
        System.out.println("Before sorting: " + numbers);
        
        Collections.sort(numbers);
        
        System.out.println("After sorting: " + numbers);
    }
}

In this example, we first create an ArrayList called numbers and add some integers to it. We then print the list before sorting using System.out.println(). We then sort the list using the Collections.sort() method and print it again after sorting.

The output of this code will be:

Before sorting: [5, 2, 8, 1, 10]
After sorting: [1, 2, 5, 8, 10]

As you can see, the elements of the list have been sorted in ascending order.

It is important to note that the Collections.sort() method only works with lists that implement the List interface. If you want to sort elements of other types of collections, you can either convert them to a list first or use a different sorting method.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview โ€” then scores it.
๐Ÿ“ž Practice Java Collections โ€” free 15 min
๐Ÿ“• Buy this interview preparation book: 100 Java Collections questions & answers โ€” PDF + EPUB for $5

All 100 Java Collections questions ยท All topics