简体   繁体   中英

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:

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.

So, is it necessary, and what is the point of it?

You should use 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")
Foo<Bar>[] foo = new Foo[N];

cast is to enforce type safety. 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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM