[英]Should I 'new List[N]' or '(List<Integer>[])new List[N]' in java, when I want an array of lists of integers?
Reading Robert Sedgewick's book on algorithms, I always see him mention that in java arrays of things that hold other generic things, need to be created like so:阅读 Robert Sedgewick 的关于算法的书,我总是看到他提到在 Java 数组中包含其他通用事物的事物需要像这样创建:
Foo<Bar>[] foo = (Foo<Bar>[])new Foo[N];
So I was wondering if that cast is necessary, because when I do:所以我想知道这个演员是否有必要,因为当我这样做时:
Foo<Bar>[] foo = new Foo[N];
the compiler still seems to know that the generic type is Bar.编译器似乎仍然知道泛型类型是 Bar。
So, is it necessary, and what is the point of it?那么,是否有必要,又有什么意义呢?
You should use Foo<Bar>[] foo = new Foo[N];
你应该使用
Foo<Bar>[] foo = new Foo[N];
. .
You may get a warning like:您可能会收到如下警告:
Type safety: The expression of type Foo[] needs unchecked conversion to conform to Foo<Bar>[]
which you can hide using @SuppressWarnings("unchecked")
:您可以使用
@SuppressWarnings("unchecked")
隐藏它:
@SuppressWarnings("unchecked")
Foo<Bar>[] foo = new Foo[N];
cast is to enforce type safety. cast 是为了强制类型安全。 first line doesn't compile, because the type is wrong.
第一行不编译,因为类型错误。 second one compiles fine, but most probably will error out during runtime.
第二个编译正常,但很可能会在运行时出错。
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> {}
}
There is really no difference between those two.这两者之间真的没有区别。 Both require unchecked casts.
两者都需要未经检查的强制转换。 You should not mix arrays and generics.
您不应该混合使用数组和泛型。 Unchecked casts undermine the whole purpose of generics.
未经检查的强制转换破坏了泛型的整个目的。 It will lead to ClassCastExceptions in unexpected places.
它会在意想不到的地方导致 ClassCastExceptions。 For example:
例如:
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.