liveBook · Manning

List

As explained in 100 Java Mistakes and How to Avoid Them

List is the Java collection interface for an ordered sequence of elements that may contain duplicates.

List represents an ordered sequence that may contain duplicates. Its content-based equals() comparison requires the other object to implement List and contain equal elements in the same order. section 7.2

Use List carefully around these common boundaries:

  • Do not pass a primitive array to Arrays.asList(). Generic varargs inference wraps the entire array as one element, producing a List<int[]> rather than a list of integers; contains(0) therefore returns false. section 2.9.3
  • Remember that List.equals() compares content, while wrappers typed only as unmodifiable Collection do not necessarily preserve List equality behavior. section 7.2
  • Do not assume every List accepts contains(null). Factory methods such as List.of() reject null search arguments, so guard nullable values before searching. section 8.3

A primitive-array search that never finds zero

For an int[] arr, Arrays.asList(arr).contains(0) searches a one-element list whose element is the original int[] array. Declare intermediate variables explicitly or use a conversion that produces element values. section 2.9.3

static boolean containsZero(int[] arr) {
    return Arrays.asList(arr).contains(0);
}

Inspect the compact failure pattern where a primitive array is passed directly to Arrays.asList(). section 2.9.3

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2, 3);
System.out.println(list1.equals(list2));    #1

Compare two Lists with equal elements to see content-based equality in action. section 7.2

Set<String> PLATFORMS = Set.of("PC", "Mac", "Mobile");

Examine the concise factory form whose null-hostile behavior can differ from older unmodifiable collections. section 8.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains varargs internals, boxing, equality requirements, null behavior, defensive fixes, and static-analysis limits.
Examples
Uses Arrays.asList() searches, equal integer lists, unmodifiable collections, and null-sensitive collection factories.
What it assumes
Assumes familiarity with Java generics, arrays, boxing, equals(), collection interfaces, and nullable values.
What you can do after
Diagnose misleading array searches, choose compatible equality comparisons, guard nullable membership tests, and heed analyzer warnings.
How it connects
Connects List to arrays, generics, boxing, equals(), streams, sets, collection factories, and unmodifiable wrappers.

Also explained in

Compare how 21 books explain list →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.