Why Didn't The Creators Of Java Allow For Generic Array Intialization?

Discussion in 'Java' started by res7cxbi@verizon.net, Jan 2, 2006.

  1. Guest

    Just Curious...

    Why can't i initialize a generic array like this?

    private E[] data = new E[10];

    This creates a compiler error saying that i can't intialize generic
    arrays
    The only workaround i've seen (the Collections class do this too) is
    this:

    private E[] data = (E[]) new Object[10];

    so the question is...

    Why Didn't The Creators Of Java Allow For Generic Array Intialization?
    , Jan 2, 2006
    #1
    1. Advertising

  2. On Sun, 01 Jan 2006 19:38:55 -0800, res7cxbi wrote:

    > Just Curious...
    >
    > Why can't i initialize a generic array like this?
    >
    > private E[] data = new E[10];
    >
    > This creates a compiler error saying that i can't intialize generic
    > arrays
    > The only workaround i've seen (the Collections class do this too) is
    > this:
    >
    > private E[] data = (E[]) new Object[10];
    >
    > so the question is...
    >
    > Why Didn't The Creators Of Java Allow For Generic Array Intialization?


    Because the instruction new E[] would have to become new Object[] (or
    whatever) "below the cover", which means that any Object reference could
    be stored. While this was once deemed appropriate (since Object [] can be
    downcast to any specific array type), it is no longer considered valid.

    So, for now we will have to explicitly agree to store any and all kinds of
    Objects (new Object[]), and create a more specific view (cast to E[]) of
    it. What is annoying is that this technique will still generate a warning
    which can only be handled with a @SuppressWarning annotation (if it is
    supported by your compiler).

    --
    You can't run away forever,
    But there's nothing wrong with getting a good head start.
    --- Jim Steinman, "Rock and Roll Dreams Come Through"
    Stefan Schulz, Jan 2, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Drak I

    Array intialization

    Drak I, Jun 23, 2004, in forum: C++
    Replies:
    5
    Views:
    2,159
    Mats Weber
    Jun 23, 2004
  2. ali

    UML creators

    ali, Jun 5, 2006, in forum: Java
    Replies:
    4
    Views:
    1,048
    Larry Barowski
    Jun 6, 2006
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,737
    Smokey Grindel
    Dec 2, 2006
  4. Eric
    Replies:
    9
    Views:
    567
    Patricia Shanahan
    Nov 22, 2006
  5. Replies:
    0
    Views:
    540
Loading...

Share This Page