Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - What's really in a unbounded wildcard?

Tags:

java

generics

If i have the following code :

public static void main(String [] args) {  
        List <Integer> l2 = new ArrayList <Integer>();  
        List <?> l3 = l2;  
        test(l2);  
        test(l3);  
}  


public static void test(List <?> l) {  
        if (l instanceof List<?>)  
            System.out.println("true");  
}  

This will print:

true  
true  

From what i understand, <?> is a reifiable type, which means it has some capture type (whatever that type is) which is available at run time.

Questions:
a. In test method, does it know that l2 has integer type (since it has been erased prior to the method call)? How does it translate so that l (from l2) is instanceof List <?>?
b. What about l3? How does it translate that?

like image 319
yapkm01 Avatar asked Dec 05 '25 10:12

yapkm01


1 Answers

I don't believe the <?> is reified. It is simply the only way to refer to a generified type without using the raw form (List). In both cases you are simply doing the exact same operation as:

if (l instanceof List) 
   ...

Edit

Indeed I have just verified that they generate absolutely identical bytecode whether you use List<?> or List in the instanceof.

like image 126
Mark Peters Avatar answered Dec 08 '25 00:12

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!