![](/img/trans.png)
[英]create list of Integers in java - cant use new List<Integer>();
[英]Should I 'new List[N]' or '(List<Integer>[])new List[N]' in java, when I want an array of lists of integers?
阅读 Robert Sedgewick 的关于算法的书,我总是看到他提到在 Java 数组中包含其他通用事物的事物需要像这样创建:
Foo<Bar>[] foo = (Foo<Bar>[])new Foo[N];
所以我想知道这个演员是否有必要,因为当我这样做时:
Foo<Bar>[] foo = new Foo[N];
编译器似乎仍然知道泛型类型是 Bar。
那么,是否有必要,又有什么意义呢?
你应该使用Foo<Bar>[] foo = new Foo[N];
.
您可能会收到如下警告:
Type safety: The expression of type Foo[] needs unchecked conversion to conform to Foo<Bar>[]
您可以使用@SuppressWarnings("unchecked")
隐藏它:
@SuppressWarnings("unchecked")
Foo<Bar>[] foo = new Foo[N];
cast 是为了强制类型安全。 第一行不编译,因为类型错误。 第二个编译正常,但很可能会在运行时出错。
public class Test {
public static void main(String[] args) {
Foo<Bar>[] foo1 = (Foo<Bar>)new Foo[] {new Foo<String>()};
Foo<Bar>[] foo2 = new Foo[] {new Foo<String>()};
}
static class Bar {}
static class Foo<T> {}
}
这两者之间真的没有区别。 两者都需要未经检查的强制转换。 您不应该混合使用数组和泛型。 未经检查的强制转换破坏了泛型的整个目的。 它会在意想不到的地方导致 ClassCastExceptions。 例如:
static class Foo<T> {
T value;
public Foo(T v) {
value = v;
}
}
public static void main(final String[] args) throws IOException {
@SuppressWarnings("unchecked")
Foo<Boolean>[] foo = new Foo[1];
((Object[])foo)[0] = new Foo<Integer>(0);
foo[0].value.booleanValue(); // runtime error will occur here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.