Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics and array initialization

What's the explanation for the following:

public class GenericsTest {
    //statement 1
    public ArrayList<Integer>[] lists;

    public GenericsTest()
    {
            //statement 2
        lists = new ArrayList<Integer>[4];
    }
}

The compiler accepts statement 1. Statement 2 is flagged by the compiler for "generic array creation".

A good explanation I've seen regarding disallowing generic arrays is this one, arguing that since arrays are covariant and generics are not you could subvert the generic typing if you allowed generic arrays.

Leaving aside the argument over whether the language should go to the extreme lengths of creating this kind of complicated inconsistency in the treatment of generics to keep you from shooting yourself no matter how hard you try (and if anyone knows of any good discussions on the relative merits/demerits of the issue please post, I'd be interested to see the arguments), why should statement (1) be allowed if (2) isn't?

like image 846
Steve B. Avatar asked Jan 22 '09 17:01

Steve B.


People also ask

How do you initialize a generic array?

reflect. Array#newInstance to initialize our generic array, which requires two parameters. The first parameter specifies the type of object inside the new array. The second parameter specifies how much space to create for the array.

Can we use generics with the array in Java?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.

Why is generic array creation not allowed in Java?

If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.

Can you create an array using a generic type parameter?

Array of generic typesNo, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.

Is it possible to initialize generic arrays?

Although we can't initialize generic arrays directly, it's still possible to achieve the equivalent operation if the precise type of information is provided by the calling code. 3. Creating a Generic Array For our example, let's consider a bounded stack data structure, MyStack, where the capacity is fixed to a certain size.

How to initialize an array in Java?

Initializing Arrays in Java. 1 1. Overview. In this quick tutorial, we're going to examine the different ways that we can initialize an array, and the subtle differences between ... 2 2. One Element at a Time. 3 3. At the Time of Declaration. 4 4. Using Arrays.fill () 5 5. Using Arrays.copyOf () More items

Is ArrayList a generic array in Java?

ArrayList Implementation Interestingly, ArrayList itself is implemented using generic arrays. Let's peek inside ArrayList to see how. Notice ArrayList uses Object as the element type. As our generic type isn't known until runtime, Object is used as the superclass of any type.

How do I implement a stack with a generic array?

As we'd like the stack to work with any type, a reasonable implementation choice would be a generic array. First, we'll create a field to store the elements of our stack, which is a generic array of type E: public MyStack(Class<E> clazz, int capacity) { elements = (E []) Array.newInstance (clazz, capacity); }


Video Answer


2 Answers

It's because you can't create, but you can use them:

public class GenericsTest {
    //statement 1
    public ArrayList<Integer>[] lists;

    public GenericsTest()
    {
        //statement 2
        lists = new ArrayList[4];
        //statement 3
        lists[0].add(new Integer(0));
        //statement 4
        lists[0].add(new String(""));
    }
}

Statement 3 is possible, statement 4 will lead to a compiler error.

like image 200
Sven Lilienthal Avatar answered Oct 25 '22 15:10

Sven Lilienthal


There seems to be obscure cases where you could inadvertently cause a ClassCastException as explained here http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (section 7.3)

an intersting discussion on this topic could be found here http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=324.msg1131.html

like image 24
user54579 Avatar answered Oct 25 '22 17:10

user54579