5 Replies Latest reply: Oct 18, 2010 11:47 AM by 452196 RSS

    Cannot create generic array

    806215
      The following statement is flagged as an error by Eclipse:

      ArrayList<Card>[] items = new ArrayList<Card>[52];

      The statement seems fine to me. What is the problem? Thanks
        • 1. Re: Cannot create generic array
          802205
          What's the error?
          • 2. Re: Cannot create generic array
            abillconsl
            803212 wrote:
            The following statement is flagged as an error by Eclipse:

            ArrayList<Card>[] items = new ArrayList<Card>[52];

            The statement seems fine to me. What is the problem? Thanks
            That would be because it's incorrect syntax. Recheck the API doco on ArrayList.

            Correcting myself, I see you actually want to create an array of ArrayLists, whereas I had thought you wanted to create a pre-sized ArrayList.

            So the problem has to do with creating a Generic array.
            • 3. Re: Cannot create generic array
              jduprez
              The following statement is flagged as an error by Eclipse:

              ArrayList<Card>[] items = new ArrayList<Card>[52];
              Generic arrays are explicitly forbidden by the java Language Specifications.
              Section [url http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.3]10.2: It is a compile-time error if the element type is not a reifiable type

              Reifiable is defined in section [url http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#112581]4.7.
              • 4. Re: Cannot create generic array
                802316
                Generics and arrays don't always play nicely together.
                You have to create an array of the base type and cast it to the generic type. (Which will give you a warning which you have to disable or ignore)

                I believe there are good academic reasons it is implemented this way.
                But pragmaticly its a very poor design choice IMHO and adds no value.
                • 5. Re: Cannot create generic array
                  452196
                  They couldn't work out a way to preserve type safety in a generic array. Almost always it's best to replace the array with another List making the type
                  List<List<Card>> items = new ArrayList<List<Card>>(52);