Search code examples
javagenericstype-erasure

Java Generics - method after type erasure


How will the following method look after applying type erasure?

static<T> void InsertAt0(List<T> mylist, T element) {
    mylist.add(0, element);
}

will T be replaced with Object? or maybe type-erasure is only about generics classes?


Solution

  • Just remove all of the <T>s, and then replace any T with Object:

    static void InsertAt0(List mylist, Object element) {
       mylist.add(0, element);
    }
    

    Note that mylist above has been erased to its raw type equivalent: List<T> became just List.

    If you had specified a wildcard bound for T, like <T extends Number>, then you would replace T with that bound instead of Object:

    static void InsertAt0(List mylist, Number element) {
                                       ^^^^^^