liveBook · Manning

Contains

As explained in 100 Java Mistakes and How to Avoid Them

Collection.contains is the Java Collection interface method that tests whether a collection contains an object equal to a specified value.

Collection.contains(Object) tests whether a collection contains an element equal to the supplied value. Its Object parameter permits calls that compile even when the argument cannot match the collection’s element type. section 8.1

Primitive arrays become one list element

Passing a primitive array to Arrays.asList creates a list containing the entire array, not its primitive elements. Therefore Arrays.asList(arr).contains(0) searches for an Integer inside a List<int[]> and returns false. Declare an intermediate variable with its intended type so this mismatch becomes visible. section 2.9.3

Avoid contains failures that compile cleanly:

  • Check that the searched object has the same semantic type as the stored elements; mixing File, Path, and String path representations produces a not-found result rather than an immediate error. section 8.1
  • Do not assume a Collection declaration reveals null behavior. Some collections return false for contains(null), while others throw NullPointerException; use obj != null && collection.contains(obj) when null is possible. section 8.3
  • Review warnings for incompatible collection calls; IntelliJ IDEA reports them through Suspicious Collections Method Calls, and SonarLint provides rule S2175. section 2.9.3

The same expression can change behavior after replacing an older unmodifiable collection with List.of or Set.of: a nullable search argument may change from false to NullPointerException. section 8.3

static boolean containsZero(int[] arr) {
  List<int[]> list = Arrays.asList(arr);
  return list.contains(0);
}

Inspect the inferred List<int[]> declaration that makes the failed primitive-array search apparent. section 2.9.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the Object parameter, varargs inference, semantic type mismatches, null policies, and static-analysis support.
Examples
Uses primitive arrays, File-versus-Path collections, nullable searches, and List.of or Set.of migrations.
What it assumes
Assumes familiarity with Java collections, generics, arrays, boxing, and basic equality semantics.
What you can do after
Diagnose false membership results, guard nullable arguments, expose inferred types, and interpret relevant analyzer warnings.
How it connects
Connects contains with Arrays.asList, generics, equals, collection factories, File, Path, and null handling.

Also explained in

Compare how 2 books explain contains →

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.