Course contentsShow
← Java
Lesson 964 of 2,87022. Generics: Bounds and WildcardsFree lesson

Cannot Overload Methods Differing Only by Type Parameters

See how methods like 'void print(List<String>)' and 'void print(List<Integer>)' erase to identical signatures causing conflicts.

Cannot Overload Methods Differing Only by Type Parameters

What you'll learn: Why you can't create two methods with the same name that differ only in their generic type parameters.


The Problem

You might think you could overload methods like this:

public void print(List<String> list) {
    // print strings
}

public void print(List<Integer> list) {
    // print integers
}

This looks reasonable — two different methods for two different types, right? Wrong. The compiler will reject this code with an error.

Why This Fails: Type Erasure Strikes Again

Remember that type erasure removes all generic type information at compile time. Both of these methods erase to exactly the same signature:

public void print(List list)  // after erasure
public void print(List list)  // after erasure — duplicate!

The JVM sees two identical methods, which is illegal. Method overloading requires different parameter types after erasure, but List<String> and List<Integer> both become just List.

The Workaround

If you need different behavior for different types, use a single method with bounded type parameters or wildcards:

public <T> void print(List<T> list) {
    for (T item : list) {
        System.out.println(item);
    }
}

Or differentiate by using completely different parameter types (not just different type arguments):

public void print(List<String> list) { }
public void print(Set<String> set) { }  // OK - List vs Set

Key Takeaway: You cannot overload methods that differ only in their generic type arguments because type erasure makes their signatures identical at runtime—List<String> and List<Integer> both become List after compilation.