Video in progress
Why don't these two overloads compile, and how do you fix them?
class Importer {
void process(List<String> lines) { ... }
void process(List<Long> ids) { ... }
}
Generic types are erased: both methods become process(List) in bytecode. Two methods with the same erasure can't live in one class, so you get a "name clash" error. The fix is to give the methods different names or wrap the parameter in a concrete type.
📖 Answer
The compiler message is roughly: name clash: process(List<Long>) and process(List<String>) have the same erasure.
The reason: the JVM doesn't know about generic parameters. The method descriptor is (Ljava/util/List;)V for both. Overload resolution happens at compile time, but the result still has to be distinguishable in the bytecode.
Ways to fix it:
void processLines(List<String> lines) { ... }
void processIds(List<Long> ids) { ... }
Or turn the concept into a type:
record CustomerIds(List<Long> values) {}
void process(CustomerIds ids) { ... }
The second option is often better: the type itself tells you what List<Long> means.
Other limits that come from the same erasure:
- you can't write
instanceof List<String>(onlyList<?>); new T()andnew T[n]are not possible;- a class can't implement both
Comparable<A>andComparable<B>.
So an API design that relies on generic overloads doesn't work in Java. Tell them apart by name or by type.
Sign up to mark studied questions and save your progress.