问题描述
代码:
列表< ;?扩展Integer> ints = new ArrayList< Integer>();
ints.add(3); //错误
我还是不明白它是如何工作的。 问题:
什么意味着 CAP#1 ?它是参考类型吗?我认为,不,因为CAP#1没有继承自 Object 。我们可以编写 ints.add(null); // OK ,但我们没有编译时错误。但是我们不能写 null instanceof CAP#1; //编译时错误。为什么我们不能实例化 CAP#1 :
CAP#1 c =新的CAP#1();
从 CAP#1 出现了吗?
CAP#1 是隐式类型变量的编译器名称由'?'。没有这种命名类型,但编译器需要为该类型创建一个占位符以完成其工作。这个名字代表捕获。
它有助于精神上重写类型,如 G 。
不能使用通配符扩展类型将任何内容添加到列表中,因为您不知道什么通配符代表。就像你不能将一个 Snake 添加到一个 List< Mammal> ,你不能将它添加到 List< ?由于?可能会代表 Mammal 。
扩展动物> >然而,您可以在这种情况下始终添加 null ,因为 null 实际上是每个引用类型的成员,它必然包含?可能代表的任何内容。
我经常想知道为什么Java不处理 List< ?对于某些最终类型< code> F< / code>与< code>列表< F> 。也许这是因为 F 本身可能是通用通配符类型,这意味着它仍然会有任意多个子类型。
除了Angelika Langer关于Java泛型的着名FAQ,我一直在编译在我自己的列表中。
Code:
List<? extends Integer> ints= new ArrayList<Integer>(); ints.add(3);//error
I still dont understand how it works. Question:
What does mean CAP#1? Is it a reference type? I think, no, because CAP#1 doesnt inherited from Object. We can write ints.add(null);//OK and we havent compile time error. But we cant write null instanceof CAP#1;//compile-time error. Why we cant instanciate CAP#1:
CAP#1 c= new CAP#1();
From what CAP#1 appears?
CAP#1 is the compiler's name for the implicit type variable represented by the '?'. There is no such named type, but the compiler needs to create a placeholder for the type in order to complete its work. The name stands for "capture".
It helps to mentally rewrite a type like G<? extends T> to ∃CAP#1 extends T: G< CAP#1 >.
You can't add anything to a list with a wildcard extends type, because you don't know what that wildcard stands for. Just like you can't add a Snake to a List< Mammal >, you can't add it to a List< ? extends Animal > because that ? might turn out to represent Mammal.
You can, however, always add null in this situation because null is effectively a member of every reference type, which necessarily includes whatever the ? could possibly represent.
I've often wondered why Java doesn't treat List< ? extends F > for some final type F the same as List< F >. Maybe it's because F could itself be a generic wildcard type, which would mean it would still have arbitrarily many subtypes.
Aside from Angelika Langer's famous FAQ about Java generics, I've been compiling some things about them in my own list.
这篇关于通配符,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!