Collections and Arrays utilities
Two classes of static methods do the small jobs: java.util.Collections works on collections and java.util.Arrays on arrays. Neither is a collection itself, and both are old: some of their methods have a modern equivalent in the factory methods of List and Set. This lesson covers the ones still worth calling, the read-only view that is easy to misunderstand, and the fixed size of Arrays.asList.
A read-only view
Collections.unmodifiableList returns a view that refuses every change, and it is a view, not a copy: a change through the original list is visible through it. The program changes the original, tries to change the view, and prints the three factory lists:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReadOnly {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(names);
System.out.println(view);
names.add("c");
System.out.println(view);
try {
view.add("d");
} catch (UnsupportedOperationException e) {
System.out.println("view add: " + e.getClass().getSimpleName());
}
System.out.println(Collections.emptyList());
System.out.println(Collections.singletonList("solo"));
System.out.println(Collections.nCopies(3, "x"));
}
}
javac -Xlint:all ReadOnly.java
java ReadOnly
[a, b]
[a, b, c]
view add: UnsupportedOperationException
[]
[solo]
[x, x, x]
The second line is the point: the view shows the new element because it reads the same list. That is what makes the method cheap and what makes it dangerous as a promise: a caller who keeps the view can still see the contents change. A copy is List.copyOf(names), which cannot change at all.
frequency, swap and shuffle
The three most used methods of Collections after the sort are a count, an exchange of two positions and a shuffle. The shuffle takes a Random, and a seeded one makes the output of a run repeatable:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Utilities {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(3, 1, 2, 3, 3));
System.out.println(Collections.frequency(numbers, 3));
System.out.println(Collections.max(numbers) + " " + Collections.min(numbers));
Collections.reverse(numbers);
System.out.println(numbers);
Collections.swap(numbers, 1, 2);
System.out.println(numbers);
Collections.shuffle(numbers, new java.util.Random(7));
System.out.println(numbers);
Collections.sort(numbers);
System.out.println(numbers);
}
}
javac -Xlint:all Utilities.java
java Utilities
3
3 1
[3, 3, 2, 1, 3]
[3, 2, 3, 1, 3]
[3, 1, 3, 3, 2]
[1, 2, 3, 3, 3]
The three threes are counted, the largest and the smallest are read, and the reverse turns the list around. The swap exchanges the two positions 1 and 2, which are 3 and 2. The shuffled line is the order seed 7 gives in this JDK; another seed or another release gives another order, which is why a program that prints it is either a demonstration or a test with a fixed seed.
The Arrays class
The same sort and search exist for arrays of primitives, where a list cannot help because a List<Integer> boxes every element. Arrays.copyOf grows an array and pads it with zeros, and Arrays.fill with a range writes one value:
import java.util.Arrays;
import java.util.List;
public class ArraysUses {
public static void main(String[] args) {
int[] numbers = {3, 1, 2};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.binarySearch(numbers, 2));
int[] bigger = Arrays.copyOf(numbers, 5);
Arrays.fill(bigger, 4, 5, 9);
System.out.println(Arrays.toString(bigger));
System.out.println(Arrays.equals(numbers, new int[] {1, 2, 3}));
List<String> list = Arrays.asList("a", "b");
list.set(0, "z");
System.out.println(list);
try {
list.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("asList add: " + e.getClass().getSimpleName());
}
}
}
javac -Xlint:all ArraysUses.java
java ArraysUses
[1, 2, 3]
1
[1, 2, 3, 0, 9]
true
[z, b]
asList add: UnsupportedOperationException
binarySearch answers 1 for the value 2, which is its index in the sorted array. The copy has five slots, the three values, a zero from the padding and a nine from the fill of the range from index 4 up to but not including 5. Arrays.equals compares the contents rather than the two references, which is what == would do on arrays.
asList and its limit
Arrays.asList wraps the array in a list of fixed size: set writes through to the array and add or remove throw, because the size of an array cannot change. The last two lines of the program show both halves.
The wrapper is the reason to call the method or to avoid it. It is the shortest way to pass an array to code that wants a List, and it is a trap for code that assumes a list can grow. New code writes List.of(...) for a fixed list and new ArrayList<>(...) for a growable one.
A view or a copy
Every method of this lesson returns a view, a wrapper or a new array, and the distinction is what a caller needs. A view shares the data and costs nothing; a copy owns its data and can be changed without touching the original. The read-only methods of Collections and Arrays.asList are views. copyOf, List.copyOf and the ArrayList constructor are copies.
The mutating methods of Collections, such as sort, reverse and shuffle, change the list they are given and return nothing, which is why the program prints the list after each call. The modern style writes list.sort(...) instead of Collections.sort(list); both are the same method.
Exercises
- Make a read-only view of a list, change the original twice and print the view after each change.
- Shuffle the same list with two different seeds and print both orders.
- Count the frequency of the empty string in a list of words.
- Copy an array of four values into six slots and print it before and after a fill.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Collections.unmodifiableListreturn?Answer
A view that refuses changes, which still shows changes to the original
It wraps the list, so reads see the current contents and writes throw.
-
What does
Collections.frequencyanswer?Answer
How many elements equal the argument
It counts the elements equal to the value it is given.
-
What does
Arrays.asListreturn?Answer
A fixed-size list view of the array, where set works and add throws
The wrapper has the size of the array, so set writes through and add cannot.
-
What does this program print?
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Q1 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(List.of(1, 2, 2, 3, 2)); System.out.println(Collections.frequency(list, 2)); System.out.println(Collections.max(list)); } }Answer
3 / 3
The value 2 appears three times, and the largest element is 3.
-
What does this program print?
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Q2 { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("a", "b", "c")); Collections.reverse(list); System.out.println(list); Collections.swap(list, 0, 2); System.out.println(list); } }Answer
[c, b, a] / [a, b, c]
The reverse turns the list, and the swap of the ends turns it back.
-
What does this program print?
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Q3 { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("a", "b")); List<String> view = Collections.unmodifiableList(list); list.add("c"); System.out.println(view.size()); try { view.add("d"); } catch (UnsupportedOperationException e) { System.out.println("refused"); } } }Answer
3 / refused
The view shows the added element, and its own add is refused.
-
What does this program print?
import java.util.Arrays; public class Q4 { public static void main(String[] args) { int[] a = {1, 2}; int[] b = Arrays.copyOf(a, 4); System.out.println(Arrays.toString(b)); System.out.println(b.length); } }Answer
[1, 2, 0, 0] / 4
The copy has the new length and the extra slots keep the default value of the type.
-
What does this program print?
import java.util.Arrays; import java.util.List; public class Q5 { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b"); list.set(1, "z"); System.out.println(list); try { list.remove(0); } catch (UnsupportedOperationException e) { System.out.println("no remove"); } } }Answer
[a, z] / no remove
set writes through the wrapper and remove needs a size change, which it refuses.
-
Which call makes a copy of an array?
Answer
Arrays.copyOf
copyOf allocates a new array of the requested length and copies the values in.
-
Why does
Collections.shuffle(list, new Random(7))print the same order twice?Answer
The seeded random generator follows the same sequence every run
The order is a function of the seed, so the same seed gives the same permutation.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev