运行时无界通配符类型如何工作? [英] How unbounded wildcard types work at runtime?

查看:105
本文介绍了运行时无界通配符类型如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道无界通配符类型将被擦除并替换为Object vy类型擦除,并且无界通配符类型是可运行时可用的可重用类型。我知道列表与LT;对象> ,List,List<?> 。我知道在编译时什么是 List<?> 。我知道 List<?> 存储未知类型。
我知道它具有很强的编译时安全性和灵活性,但我想知道运行时会发生什么。

但我无法理解List<>是在运行时。



是对象引用的列表吗?
是原始类型List吗?



例如

 列表与LT;?> list = new ArrayList< Integer>(); 

在运行时列表是什么以及如何表现?



我读过所有的java语言规范,请不要只扔一个常见问题到我的脸上。



请注意,我阅读以下问题,但我没有找到我的答案(可以重复)

泛型Java,无界通配符

解决方案

好吧,在你的例子中,你的通配符是 not 无界的。 / p>

 列表<?> list = new ArrayList< Integer>(); 




在运行时列表是什么以及如何表现?


在运行时,您的列表是一个 ArrayList 的实例,它包含整数对象。链接的问题对于有通配符时会发生什么有很好的答案。请注意以下内容:

 列表<?> list = new ArrayList<?>(); 

不会进行编译,但会出现以下错误:

 无法实例化类型ArrayList<?> 

在接口中接受通配符,但您将无法实例化任何对象直接使用通配符。你必须以某种方式在你的实现中的某个地方告诉你的接口你希望他保持什么类型的对象。即使它意味着 List< Object>


I am aware of that unbounded wildcard type is going to be erased and replaced with Object vy type erasure and unbounded wildcard types are the reifiable type which type information is fully available at runtime.I know difference between List<Object> , List, List<?>. I know what is the List<?> at compile time. I know that List<?> store unknown type. I know it has strong compile-time safety and flexibility but I want to know what happens in runtime.

But I cannot understand what List<?> is at runtime.

Is it list of object references? Is it raw type List?

For example

List<?> list = new ArrayList<Integer>();

What is the list at runtime and how to behave?

I read all java language specification please don't throw just an FAQ to my face.

Note that I read following Questions and I do not find my answer(can be duplicate)

Generics Java, unbounded wildcard

解决方案

Well, in your example your wildcard is not unbounded.

List<?> list =new ArrayList<Integer>();

What is the list at runtime and how to behave?

At runtime, your list is an instance of ArrayList which holds Integer objects. The question you linked holds a pretty good answer about what happens when you have a wildcard. Note that the following:

List<?> list = new ArrayList<?>();

Won't compile, with the following error thrown at you:

Cannot instantiate the type ArrayList<?>

A wildcard is accepted when it comes to interfaces, but you won't be able to instantiate any object "directly" with a wildcard. You'll have to somehow, somewhere in your implementation, tell your interface what type of objects you want him to hold. Even if it means List<Object>.

这篇关于运行时无界通配符类型如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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