Java泛型 - 真正的无界通配符是什么? [英] Java Generics - What's really in a unbounded wildcard?

查看:239
本文介绍了Java泛型 - 真正的无界通配符是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

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



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

这将打印:

  true 
true

理解,<?> 是一个可定义的类型,这意味着它有一些捕获类型(不管那种类型是什么),它在运行时可用。



问题:

a。在测试方法中,它是否知道l2具有整数类型(因为它在方法调用之前已被擦除)?它是如何翻译的,以便l(来自l2)是instanceof List <?>?

b。那么L3呢?我不相信<?>

code>被通用化。这只是在不使用原始表单( List )的情况下引用generified类型的唯一方法。在这两种情况下,您只需执行完全相同的操作即可:




编辑



的确,我刚刚验证过无论您在中使用 List <?>> List instanceof


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?

解决方案

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.

这篇关于Java泛型 - 真正的无界通配符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆