未绑定通配符和原始类型之间的区别 [英] Difference between an unbound wildcard and a raw type

查看:252
本文介绍了未绑定通配符和原始类型之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关泛型的知识,我不明白需要使用未绑定的通配符,以及它与原始类型的区别。我阅读了这个问题但仍然没有明确表示。在未绑定通配符的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() or List.clear(). In fact, Class<?> is so often used because most of the methods in Class<T> do not depend on T.

请解释非结合通配符和外行语言的原始类型之间的差异。

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屋!

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