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



















