【发布时间】:2020-12-09 07:57:07
【问题描述】:
此代码有效。它编译并运行时会出现“未经检查或不安全的操作”警告。
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>();
}
}
我遇到的错误如下:
线程“main”中的异常 java.lang.ClassCastException: class [Ljava.lang.Object;不能转换为类 [LFoo$FooItem; ([Ljava.lang.Object; 位于加载器'bootstrap' 的模块 java.base 中;[LFoo$FooItem; 位于加载器 com.sun.tools.javac.launcher.Main$MemoryClassLoader 的未命名模块中
这是为什么?
【问题讨论】:
-
"these 2 don't compile"具有误导性。您得到的是运行时异常,而不是编译器错误。 -
你是对的,它们实际上是编译的!我已编辑问题以将其声明为运行时错误。
-
Java 和 C# 中的数组差异刚刚被破坏。 web.archive.org/web/20100629084706/http://blogs.msdn.com/b/…
标签: java