未绑定通配符和原始类型之间的区别 [英] Difference between an unbound wildcard and a raw type
问题描述
我正在阅读有关泛型的知识,我不明白需要使用未绑定的通配符,以及它与原始类型的区别。我阅读了这个问题但仍然没有明确表示。在未绑定通配符的Java教程页面中,我得到了两个点和我不明白第一点:$ b
$ b
I was reading about generics and I did not understand the need for unbound wildcards and how it differs from raw type. I read this question but still did not get it clearly. In the Java tutorial page for unbound wildcard I got below two points and I did not understood first point:
- 如果您正在编写一个可以使用功能实现的方法提供在
Object
类中。
- 当代码在泛型类中使用不依赖于类型参数的方法时。例如,
List.size()
或List.clear()
。事实上,经常使用Class <?>
,因为Class< T>
中的大多数方法都不取决于T
。
- If you are writing a method that can be implemented using functionality provided in the
Object
class.- When the code is using methods in the generic class that don't depend on the type parameter. For example,
List.size()
orList.clear()
. In fact,Class<?>
is so often used because most of the methods inClass<T>
do not depend onT
.
请解释非结合通配符和外行语言的原始类型之间的差异。
Can someone please explain the difference between unbound wildcard and raw type in layman language.
List<?>
from List< Object>
?
推荐答案
List<>
与List< Object>
主要区别在于第一行编译但第二行不行:
The main difference is that the first line compiles but the second does not:
List<?> list = new ArrayList<String> ();
List<Object> list = new ArrayList<String> ();
但是,由于您不知道 List的通用类型<
However, because you don't know what the generic type of List<?>
is, you can't use its parameterized methods:
List<?> list = new ArrayList<String> ();
list.add("aString"); //does not compile - we don't know it is a List<String>
list.clear(); //this is fine, does not depend on the generic parameter type
至于与原始类型的区别(没有泛型),下面的代码编译并运行正常:
As for the difference with raw types (no generics), the code below compiles and runs fine:
List list = new ArrayList<String> ();
list.add("aString");
list.add(10);
这篇关于未绑定通配符和原始类型之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!