java - instanceof List 和 instanceof List<?> 的区别

标签 java generics collections type-erasure erasure

<分区>

我知道我们不能调用 instanceof List<E>因为List<E>不是可具体化的类型。两者 instanceof Listinstanceof List<?>工作;然而 Eclipse IDE 建议使用 instanceof List<?> .

我想知道为什么它建议未绑定(bind)通配符 instanceof List<?>而不是原始调用 instanceof List .是否未绑定(bind)通配符 instanceof List<?>比原始调用有任何优势 instanceof List

提前致谢。

编辑 1:实际上,instanceof Listinstanceof List<?>与编译器在编译时会删除类型相同。但除了 Mena 指出的美观原因之外,它还有其他使用原因吗 instanceof List<?>赞成instanceof List

编辑 2:根据 this entry来自甲骨文:

  1. The type of an instanceof/cast expression is raw

This happens very frequently, as javac forbids instanceof expressions whose target type is a generic type; for casts, the compiler is slightly more permissive since casts to generic type are allowed but a warning is issued (see above). Anyway, the raw type should be replaced by an unbounded wildcard, as they have similar properties w.r.t. subtyping.

Object o = new ArrayList<String>(); List<?> list_string = (List)o; //same as (List<?>)o boolean b = o instanceof List; //same as o instanceof List<?>

因此,我们可以推断,除了 Mena 所说的美容原因和使用基因的限制外,instanceof Listinstanceof List<?>是相同的。

最佳答案

List<E> 不是可具体化的类型”并不是表述为什么 instanceof 的最佳方式不会编译。

instanceof运算符在运行时验证对象的类型。

因此,type erasure防止 Java 知道其参数化类型(<> 之间的类型)。

因此原始 List (相当于 List<Object> )或 List<?> (即未知类型的 List)在这里实际上意味着相同,尽管通常建议不要使用原始语法(在这里,出于美观原因)。

关于java - instanceof List 和 instanceof List<?> 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827717/

相关文章:

java - Android:尝试在空对象引用上调用虚拟方法 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'

c# - 需要有关我缺少的代码输出的说明

java - Smali - 如何在此代码中编辑点击时的 url

Java 并发查询同一表以进行电子邮件处理

java - 为什么synchronizedCollection()静态工厂方法的输入参数中没有有界通配符?

c++ - 通用回调

c# - 使用泛型类的参数作为事件类型

java - 如何在java中获取Map中重复键的最新值?

vba - VBA中判断一个对象是否是集合的成员

java - 提交并关闭事务后,将新类添加到图表中 - 新的 Tx 在模式中看不到该类,尽管它已被持久化