Skip to content

Where the type went

The situation

A team writes a generic repository:

```java class Repository<T> { private final List<T> items = new ArrayList<>();

void add(T item) { items.add(item); }

// Intended: return every stored item that is a Student List<Student> students() { List<Student> out = new ArrayList<>(); for (T item : items) { if (item instanceof Student) out.add((Student) item); } return out; } } ```

Elsewhere, a developer writes:

java Repository<Student> repo = new Repository<>(); List<Object> raw = (List) someMethodReturningRepositoryItems(); raw.add("not a student");

The code compiles with a warning. At runtime a ClassCastException is thrown, but not on the line that added the string.

Why does adding a String to a List<Student> through a raw reference not fail immediately?