Does the parameter introduce a role parameter?

Suppose I have a generic Parcel class and a generic delivery method as shown in the code below. The method prints and returns x, which is assigned a parameter of type Integer inside the method.

public class Parcel<T> { public <X> X deliver(){ X x = (X) new Integer(100); System.out.println(x); return x; } } 

Inside the main, I call the deliver method by passing the Parcel parameter. However, it still prints 100.

 public static void main(String args[]) { Parcel<String> parcel = new Parcel<>(); System.out.println(parcel.<Parcel> deliver()); } 

This means that an argument of type Parcel passed in the print line does not play any role, and I expected an exception here. How it works?

+5
source share
1 answer

What you are observing is called the erase type . General parameters are used by the compiler to ensure correct input and are not displayed at run time.

In general, nothing prevents you from doing this trick:

 List<Integer> list = new ArrayList<>(); list.append(""); // produces compiler error // just drop that "useless" generic argument List erased = (List) list; erased.append(""); // works fine 

EDIT

Actually my original answer was sometimes for implementing Parcel

 public class Parcel<T> { public T deliver(){ T x = (T) new Integer(100); System.out.println(x); return x; } } 

But the key idea for <X> X deliver() is the same:

 Object parcel = parcel.<Parcel> deliver(); // erased, works ok Parcel parcel = parcel.<Parcel> deliver(); // java.lang.ClassCastException 
+1
source

All Articles