此代码有效。它会编译并以“未经检查或不安全的操作”警告运行。
class Foo<T> {
T[] items = (T[]) new Object[10];
public static void main(String[] args) {
Foo<Integer> foo = new Foo<Integer>();
}
}
虽然这两个给我运行时错误
class Foo<T> {
class FooItem { T item; }
FooItem[] items = (FooItem[]) new Object[10];
public static void main(String[] args) {
Foo<Integer> foo = new Foo<Integer>();
}
}
class Foo<T> {
static class FooItem<E> { E item; }
FooItem<T>[] items = (FooItem<T>[]) new Object[10];
public static void main(String[] args) {
Foo<Integer> foo = new Foo<Integer>();
}
}
我遇到的错误如下:
线程“主”中的异常java.lang.ClassCastException:类[Ljava.lang.Object; 不能转换为类[LFoo $ FooItem; ([[Ljava.lang.Object;位于装载程序'bootstrap'的模块java.base中; [LFoo $ FooItem;位于装载程序com.sun.tools.javac.launcher.Main $ MemoryClassLoader的未命名模块中
为什么是这样?
您的Foo
课程的所有版本都有相同的问题。Type safety: Unchecked cast from Object[] to X
您将忽略的警告仅显示其在执行过程中不同阶段的后果。
这是打破第一个版本的方法:
class Foo<T> {
T[] items = (T[]) new Object[10];
public static void main(String[] args) {
Foo<Integer> foo = new Foo<Integer>();
Integer i = foo.items[1] * 2;
}
}
它崩溃与...同样的问题:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at stackoverflow.Foo.main(Main.java:17)
为什么?因为(T[]) new Object[10];
在编译时执行,即编译器不知道如何验证之间的关系T[]
和Object[]
正如你可以不投new Object()
给Integer
,你可以不投new Object[10]
给Integer[]
。只是该类强制转换异常仅在运行实际强制转换时显示。对于第一个代码段,它不会在声明语句上运行T[] items = (T[]) new Object[10];
(因此出现警告),但是将whenitems
用作type参数的含义T
。
您的其他版本只是因为将其转换为具体类型(例如)(FooItem[]) new Object[10]
,导致声明语句本身崩溃,所以较早显示此问题。
为什么编译器允许这种强制转换?因为类型关系是有效的,所以给定这样的代码
Object[] items = new Integer[10];
Integer[] i = (Integer[])items;
Integer val = i[0];
有效且受支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句