QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Collections and test data

List, Set, Map and generics in test data

List keeps order and allows duplicates, Set holds only unique elements, and Map stores key-value pairs with unique keys. Pick a collection by the guarantee the check needs: the order of HashSet and HashMap is not guaranteed, so tests must not rely on it. List.of returns an immutable list, and Arrays.asList returns a fixed-size one. Generics check types at compile time, but the type parameter is erased at runtime.

Java · Data

A test builds expected data with List.of and appends an element. It fails on add, not on the check.

A helper returns the expected list of roles through List.of("admin", "user"). Another test takes it and adds "guest" for its scenario: UnsupportedOperationException. A third gets a list of 12 table rows from findElements, removes the empty ones in a for-each loop and catches ConcurrentModificationException. A fourth compares a sorted list with what the UI returned and fails on Ukrainian letters, although the data is right.

These are errors not of test logic but of choosing a collection and of knowing what it promises. This lesson covers when to take List, Set and Map, what limits the "convenient" factories have and what generics give.

How it works and why it is designed so

Collections in java.util are described by interfaces, and implementations differ in their guarantees. The choice starts with the question which guarantee the test needs.

TypeOrderDuplicatesTypical use in tests
ArrayListinsertion order, access by indexallowedthe result of findElements, table rows, items of an API response
HashSetnot guaranteednouniqueness checks and comparison without order
LinkedHashSetinsertion ordernoremove duplicates and keep order
TreeSetsortednoordered unique values
HashMapnot guaranteedkeys are uniquedata by role or environment: Map<Role, User>
LinkedHashMap / TreeMapinsertion order / by keykeys are uniquea stable order in a report, data by key in order

"Not guaranteed order" means a test must not rely on it: HashSet and HashMap return elements in an order that depends on hashes, and the Set.of and Map.of factories even change the order between JVM runs. So you must not compare a map's toString() with an expected string: compare the maps themselves (maps' equals ignores order).

In List.equals order matters, in Set.equals it does not, and a list is never equal to a set: assertEquals(List.of(1, 2), Set.of(1, 2)) fails although the elements are the same. If the page does not promise an order, compare without order: assertThat(actual).containsExactlyInAnyOrder("a", "b") (AssertJ) or through a Set.

Example 1: the "immutable" factories

List<String> a = List.of("admin", "user");
a.add("guest");                // UnsupportedOperationException
List.of("a", null);            // NullPointerException: null is forbidden

List<String> b = Arrays.asList("admin", "user");
b.set(0, "root");              // allowed: the size is fixed, elements are not
b.add("guest");                // UnsupportedOperationException

List<String> c = new ArrayList<>(List.of("admin", "user"));
c.add("guest");                // allowed: a mutable copy

List<String> e = Collections.unmodifiableList(c);
c.add("x");                    // e sees "x" too: it is only a view of c

The rule is simple: if a helper returns expected data, let it return an immutable collection (List.copyOf makes an immutable copy), and whoever wants to change it makes their own copy with new ArrayList<>(...). Then a test does not spoil data used by other tests. The same goes for Collectors.toList(): the specification guarantees neither mutability nor immutability, while Stream.toList() (Java 16) returns an unmodifiable list that, unlike List.of, allows null.

Example 2: removing while iterating, and the remove trap

Removing elements in a loop

for-each

remove in the loop body

The iterator notices a change made behind its back and usually throws ConcurrentModificationException. For the second-to-last element it may not throw, and the bug hides.

removeIf

A condition instead of a loop

The collection itself removes elements that match the condition in one pass.

Figure 1. Change a collection through its own methods.
List<String> names = new ArrayList<>(List.of("a", "", "b", ""));

for (String s : names) {
    if (s.isEmpty()) names.remove(s);   // ConcurrentModificationException
}

names.removeIf(String::isEmpty);         // correct: [a, b]

List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(1);                    // index 1 -> [10, 30]
ids.remove(Integer.valueOf(10));  // value 10 -> [30]

The second block shows a trap of a list of numbers: remove(int) removes by index and remove(Object) by value, and with List<Integer> a literal picks the first. Maps are convenient to work with through the methods getOrDefault, computeIfAbsent, merge.

Map<String, Integer> counts = new HashMap<>();
for (String status : statuses) counts.merge(status, 1, Integer::sum);

Map<Role, List<User>> byRole = new EnumMap<>(Role.class);
for (User u : users) byRole.computeIfAbsent(u.role(), r -> new ArrayList<>()).add(u);

Generics move type checking to compile time: List<String> will not accept an Integer, and an element can be read without a cast. Do not use "raw" types (List without a parameter): they switch this check off. At run time the type parameter is erased (type erasure), so new T() and instanceof List<String> are impossible, and Jackson needs a TypeReference for List<User>, otherwise it returns a list of maps. Two more details: List<String> is not a subtype of List<Object>, so a method with a List<? extends Number> parameter reads a list of any numbers but does not let you add to it.

Java 21 added sequenced collections (SequencedCollection): List gained getFirst(), getLast() and reversed(), and LinkedHashSet and LinkedHashMap also give access to the first and last element. getFirst() on an empty list throws NoSuchElementException, which is more useful than the IndexOutOfBoundsException from get(0).

Limits and alternatives. A "list is sorted" test is often written as a copy through Collections.sort and a comparison. This checks the natural order of strings by character codes, not the order the user sees: for Ukrainian or German the order is set by a Collator with the right Locale, so first find out how the product itself sorts. For comparing complex objects, usingRecursiveComparison() in AssertJ is handy, so that you do not implement equals in a class only for a test.

Common mistakes

  • Changing a collection obtained from List.of, Stream.toList() or a helper that returns shared data.
  • Relying on order in HashSet, HashMap or Set.of: the test is green until the values or the JDK version change, and with Set.of it can fail on the very next JVM run.
  • remove(1) on List<Integer> instead of removing a value.
  • A raw type or a cast instead of a generic, hiding a type error until run time.
  • Comparing a list with a set through equals.

Check yourself

Why does Arrays.asList("a", "b").add("c") throw an exception while set(0, "x") does not?

Answer

The list has a fixed size: it is a window on an array. An element of an array can be replaced, but the length cannot change, so add and remove give UnsupportedOperationException.

A test takes the expected Set.of("a", "b") and compares it with List.of("a", "b") through assertEquals. What happens?

Answer

The test fails: a list is never equal to a set, even with the same elements. Compare the same kinds of collections, or without order through containsExactlyInAnyOrder.

What does ids.remove(1) do for List<Integer> ids and how do you remove the value 1?

Answer

It picks the remove(int index) overload and removes the element at position 1. To remove the value, use ids.remove(Integer.valueOf(1)).

In an interview. Junior: List keeps order and duplicates, Set only unique elements, Map key-value pairs. List.of gives an immutable list, Arrays.asList a fixed-size list. Generics check types at compile time. Middle/Senior: I choose a collection by the guarantee a check needs: without order I use containsExactlyInAnyOrder or a Set and do not rely on HashMap. I hand out shared data as immutable and change a copy. I know about type erasure (TypeReference for Jackson), about removeIf instead of removing in a loop, and that sorting in the UI may follow a Collator rather than character codes.

More articles in this chapter