When Collections.sort() encounters null elements in a list, it typically throws a NullPointerException because the sorting algorithm needs to compare elements to determine their order. Since null does not have any comparison behavior, Java cannot perform compareTo() operations on it, causing the sort process to fail.
Key Points:
• Collections.sort() expects elements to be non-null and mutually comparable. • A NullPointerException occurs when the sorting algorithm attempts to compare a null value with another element. • Lists containing null values should be cleaned before sorting or handled with a custom Comparator. • Java 8 introduced Comparator.nullsFirst() and Comparator.nullsLast() to safely sort collections containing null elements. • Using a custom Comparator provides control over where null values should appear in the sorted result.
Example:
Consider a list of employee names where some records are missing and represented as null. Directly calling Collections.sort() will fail. Using Comparator.nullsLast() can place all null values at the end of the sorted list.
Code Example:
import java.util.*;
public class NullSortingExample {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"John",
null,
"Alice",
"Bob"
);
names.sort(Comparator.nullsLast(String::compareTo));
System.out.println(names);
}
}Output:
[Alice, Bob, John, null]Interview Tip:
A concise interview answer is: "If Collections.sort() is used on a list containing null elements, it usually throws a NullPointerException because null values cannot be compared. To handle such cases, use a custom Comparator such as Comparator.nullsFirst() or Comparator.nullsLast(), or remove null values before sorting."