instanceof List 和 instanceof List<?> 的区别
The difference between instanceof List and instanceof List<?>
我知道我们不能调用 instanceof List<E>
因为 List<E>
不是可具体化的类型。 instanceof List
和 instanceof List<?>
都有效;然而 eclipse IDE 建议使用 instanceof List<?>
。
我想知道为什么它建议未绑定通配符 instanceof List<?>
而不是原始调用 instanceof List
。未绑定通配符 instanceof List<?>
是否比原始调用 instanceof List
有任何优势?
提前致谢。
编辑1:实际上,instanceof List
和instanceof List<?>
是一样的,因为编译器会在编译时擦除类型。但是除了 Mena 指出的美观原因之外,它还有其他理由使用 instanceof List<?>
来支持 instanceof List
吗?
编辑 2:根据来自 Oracle 的 this entry:
- 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 List
和 instanceof List<?>
是相同的。
可能是因为 List
是原始类型而 List<?>
不是。原始类型可能非常危险,因为它们可能有许多奇怪的副作用。
我一找到就会post参考。
List本身就是一种类型。所以如果你改变它里面的类型不会有任何区别。
"List<E>
不是可具体化的类型" 不是表述 instanceof
无法编译的最佳方式。
instanceof
运算符在运行时验证对象的类型。
因此,type erasure 阻止 Java 知道其参数化类型(<>
之间的类型)。
因此,原始的 List
(相当于 List<Object>
)或 List<?>
(即未知类型的 List
)在这里实际上是相同的,尽管通常建议不要使用原始语法(这里是出于美观原因)。
我知道我们不能调用 instanceof List<E>
因为 List<E>
不是可具体化的类型。 instanceof List
和 instanceof List<?>
都有效;然而 eclipse IDE 建议使用 instanceof List<?>
。
我想知道为什么它建议未绑定通配符 instanceof List<?>
而不是原始调用 instanceof List
。未绑定通配符 instanceof List<?>
是否比原始调用 instanceof List
有任何优势?
提前致谢。
编辑1:实际上,instanceof List
和instanceof List<?>
是一样的,因为编译器会在编译时擦除类型。但是除了 Mena 指出的美观原因之外,它还有其他理由使用 instanceof List<?>
来支持 instanceof List
吗?
编辑 2:根据来自 Oracle 的 this entry:
- 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 List
和 instanceof List<?>
是相同的。
可能是因为 List
是原始类型而 List<?>
不是。原始类型可能非常危险,因为它们可能有许多奇怪的副作用。
我一找到就会post参考。
List本身就是一种类型。所以如果你改变它里面的类型不会有任何区别。
"List<E>
不是可具体化的类型" 不是表述 instanceof
无法编译的最佳方式。
instanceof
运算符在运行时验证对象的类型。
因此,type erasure 阻止 Java 知道其参数化类型(<>
之间的类型)。
因此,原始的 List
(相当于 List<Object>
)或 List<?>
(即未知类型的 List
)在这里实际上是相同的,尽管通常建议不要使用原始语法(这里是出于美观原因)。