Collections Class in Java: Methods and Examples - Quiz
Total: 7 questions
1. What is the Collections class in Java and what methods does it have?
What is the Collections class in Java and what methods does it have?
java.util.Collections is the utility class of the Java Collections Framework that contains only static methods. Its constructor is private, so you cannot create an object; the methods are called through the class name: Collections.sort(list). Do not confuse it with the Collection interface.
The methods fall into three groups:
- algorithms over a list:
sort(),binarySearch(),reverse(),shuffle(),swap(),fill(),copy(),rotate(); - calculations over any collection:
max(),min(),frequency(),disjoint(); - factories of lists and wrappers:
nCopies(),addAll(),emptyList(),singletonList(),unmodifiableList(),synchronizedList(),checkedList().
Methods that rearrange elements change the list through set(), so they work with ArrayList, LinkedList and Arrays.asList(). Lists from List.of(), nCopies() and unmodifiableList() answer any rearrangement with UnsupportedOperationException — make a copy first: new ArrayList<>(List.of(...)). For arrays there is a similar class, Arrays.
2. Why does Collections.binarySearch() work only on a sorted list, and what does it return?
Why does Collections.binarySearch() work only on a sorted list, and what does it return?
On every step binary search compares the key with the middle element and discards half of the list — this is correct only if the list is sorted. The method returns the index of the found element, and if the element is absent — -(insertion point) - 1, where the insertion point is the position the element would take in the sorted list. You get it back with -result - 1. For an ArrayList the search takes O(log n).
List<String> list = Arrays.asList("red", "blue", "green");
System.out.println(Collections.binarySearch(list, "red")); // -4, although indexOf = 0
Collections.sort(list); // [blue, green, red]
System.out.println(Collections.binarySearch(list, "green")); // 1
System.out.println(Collections.binarySearch(list, "yellow")); // -4
Java does not check whether the list is sorted, so there is no exception — only a wrong result. If the list is sorted with a comparator, for example Collections.reverseOrder(), search with the same comparator: Collections.binarySearch(list, key, Collections.reverseOrder()).
3. How do you shuffle a list, reverse it and swap two elements with shuffle(), reverse() and swap()?
How do you shuffle a list, reverse it and swap two elements with shuffle(), reverse() and swap()?
All three methods modify the list itself and return nothing: Collections.reverse(list) reverses the order of the elements, Collections.swap(list, i, j) swaps the elements at indexes i and j, and Collections.shuffle(list) rearranges the elements randomly.
List<String> list = Arrays.asList("red", "blue", "green", "black");
Collections.reverse(list); // [black, green, blue, red]
Collections.swap(list, 0, 3); // [red, green, blue, black]
Collections.shuffle(list); // a different order on every run
To make the shuffle repeat from run to run (tests, reproducing a bug), pass a generator with a fixed seed: Collections.shuffle(list, new Random(42)). An index outside [0, size()) in swap() gives IndexOutOfBoundsException. To reverse a list without changing the original, make a copy first: new ArrayList<>(list).
4. What is the difference between Collections.fill() and Collections.nCopies()?
What is the difference between Collections.fill() and Collections.nCopies()?
Collections.fill(list, obj) replaces every existing element of the list with obj and does not change the size: an empty list stays empty after fill(). Collections.nCopies(n, obj) creates a new immutable list of n equal elements; to modify it, copy it into an ArrayList:
List<String> filled = new ArrayList<>(Collections.nCopies(3, "black"));
filled.add("white"); // [black, black, black, white]
Without the copy, add() throws UnsupportedOperationException, and nCopies(-1, "x") throws IllegalArgumentException. All positions of nCopies() refer to one object: after Collections.nCopies(3, new StringBuilder()) and get(0).append("x") the list prints as [x, x, x].
5. How do you count occurrences of an element and check whether two collections have common elements with frequency() and disjoint()?
How do you count occurrences of an element and check whether two collections have common elements with frequency() and disjoint()?
Collections.frequency(collection, obj) returns how many times an element occurs in a collection, comparing with equals(); obj = null is allowed. Collections.disjoint(c1, c2) returns true if there are no common elements (for two empty collections it is true as well). Both methods accept any Collection.
List<String> colors = Arrays.asList("red", "blue", "red", null);
Collections.frequency(colors, "red"); // 2
Collections.frequency(colors, "Red"); // 0: equals() is case-sensitive
Collections.frequency(colors, null); // 1
Collections.disjoint(colors, List.of("red", "orange")); // false
For your own classes frequency() counts correctly only if equals() is overridden. The most frequent element is found with a combination: Collections.max(list, Comparator.comparingInt(x -> Collections.frequency(list, x))), but this is O(n²) — for large data count frequencies in one pass with a HashMap.
6. What are Collections.addAll(), emptyList() and singletonList() used for?
What are Collections.addAll(), emptyList() and singletonList() used for?
Collections.addAll(collection, e1, e2, ...) adds the listed elements to an existing collection and returns true if the collection changed. For a Set that already had all the elements it returns false; for a list from Arrays.asList() it throws UnsupportedOperationException.
emptyList() and singletonList(obj) return immutable lists of zero and one element; add() on them throws UnsupportedOperationException. They are returned from methods so that no extra ArrayList is created: emptyList() hands out the same shared object every time. If the calling code has to fill the result, return new ArrayList<>().
Since Java 9, List.of() and List.of(obj) are often used instead. The difference: singletonList(null) is allowed and gives [null], while List.of(null) throws NullPointerException.
7. What are the most common mistakes when working with the Collections class?
What are the most common mistakes when working with the Collections class?
binarySearch()on an unsorted list or with a different comparator: no exception, just a wrong result (for example, a negative value for an element that is in the list).sort(),shuffle(),reverse()on a list fromList.of(),nCopies()orunmodifiableList()—UnsupportedOperationException;addAll()onArrays.asList()— the same.copy(dest, src)intonew ArrayList<>(10): what matters is not the capacity butsize(), which is 0, so you getIndexOutOfBoundsException: Source does not fit in dest. An independent copy is made withnew ArrayList<>(src).max()andmin()on an empty collection —NoSuchElementException; checkisEmpty()or usestream().max(cmp), which returns anOptional. Strings are compared by character codes, soCollections.max(Arrays.asList("cat", "dog", "Zebra"))returns"dog", andmin()returns"Zebra".fill()on an empty list adds nothing, andnCopies()with a mutable object stores the same reference in every position.frequency()for a class without an overriddenequals()compares references and does not find objects that are equal by content.
The distance in rotate() is never an error: a negative one shifts to the left, and a value larger than the size is taken modulo the size (rotate(list, 7) for five elements is the same as rotate(list, 2)).