liveBook · Manning

Generics

As explained in 100 Java Mistakes and How to Avoid Them

A generic type is a Java type declaration or use parameterized by one or more type arguments.

Generics parameterize Java types, restricting methods that add elements to a collection to its declared element type. Search and removal methods are a dangerous exception: many still accept Object, so a typed collection can receive an unrelated search argument without a compile-time error. section 8.1

The unrelated-type search mistake

A Set<File> queried with a Path compiles, but contains returns false because the collection stores File objects. Similar failures occur when File, Path, and String represent the same path in different parts of a program. Removal methods can silently remove nothing, delaying detection until production. section 8.1

Avoid the mistake by checking:

  • Whether the queried value has the same runtime representation as the collection element type. section 8.1
  • Whether refactoring has mixed legacy and newer types, especially File, Path, and String path values. section 8.1
  • Whether contains, remove, indexOf, map lookup, or bulk collection operations are being passed unrelated values. section 8.1
Set<File> allowedFiles = new HashSet<>();

boolean isAllowed(Path filePath) {
  return allowedFiles.contains(filePath);
}

Inspect the minimal File-versus-Path example to see how a generic collection can still admit an unrelated search argument. section 8.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains parameterized additions and unrestricted search APIs, but stops short of generic type-system internals.
Examples
Uses File, Path, String, List<Short>, and CharSequence-versus-Number lookup examples.
What it assumes
Assumes familiarity with Java collections and teaches why parameterized types do not constrain every collection operation.
What you can do after
Diagnose silent lookup failures by comparing collection element representations with search and removal arguments.
How it connects
Connects generics with collections, maps, refactoring, and equals-based type mismatches.

Also explained in

Compare how 20 books explain generics →

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.