Search code examples
javagenericstype-erasure

Confusion regarding the use of Type Erasure by the Compiler in certain situation


I am trying to learn Java Generics. I wrote the following code and was trying to understand how compiler apply Type erasure rules on different scenarios of codes.

Here is the code:

package GenericsTuts.G4_WildCards;

import java.util.*;

class GenericsBehaviours{
  
    <T> void sampleMethodWC(List<? extends T> tempList){}

    <T> void sampleMethod(List<T> tempList){}
}

public class G5_WildCardsBehaviours {
    public static void main(String[] args) {
         List<Integer> integerList = new ArrayList<>();

        // First Case, no error, I understand how this works, by applying the type erasure rules, compiler replaces the type parameter T with the bound class Number, thus it accepts the child class 
        obj.<Number>sampleMethodWC(integerList);
        
        // Second Case, compiler error
        obj.<Number>sampleMethod(integerList);
    }
}

I understand how the code works in the first case. However, why does not the code work in the second case? How does the compiler apply the Type Erasure rules in this case? Do they replace the T with something else other than Object or Number?


Solution

  • as @Sweeper said, Generic Types are not polymorphic and that's meant to be this way, the first one works because you declared your parameter type as ? extends T, thus it will take a inheritor, but in the second case it requires exactly a list of T, the first answer to this problem explains very well why you can't do that:

    Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?