Cannot create a generic array of ArrayList<Piece>

I'm making a chess application and I want an array of ArrayLists that contain captured pieces. Since the number of piece types is fixed I would like to have a static array where each position stores a specific piece type.

In the constructor I've written the following:

capturedPieces =new ArrayList<Piece>[7];

And the actual declaratio looks like this:

privatestatic ArrayList<Piece>[] capturedPieces;

Piece is the base class from which all the pieces are then instantiated. Eclipse seems to think that the declaration is okay, but the assignment is not. The error message is "Cannot create a generic array of ArrayList<Piece>" and I'm not sure why I'm not allowed to do this since I've explicitly stated that all the elements are of the type "Piece".

Any ideas?

/Magnus

[944 byte] By [Fylkea] at [2007-10-1 20:27:56]
# 1

import java.util.*;

class Piece {

public Piece() {}

}

class TestArrayList {

private ArrayList<Piece> test() {

return new ArrayList<Piece>();

}

/*

private ArrayList<Piece>[] test2 (int nPieces) {

// error "generic array creation"

return new ArrayList<Piece>[nPieces];

}

*/

/*

private ArrayList<Piece>[] test3 (int nPieces) {

// warning "[unchecked] unchecked conversion"

return new ArrayList[nPieces];

}

*/

@SuppressWarnings ("unchecked") // only works in JDK 6.0 - Mustang; no-op in JDK 5.0 - Tiger

private ArrayList<Piece>[] test4 (int nPieces) {

ArrayList<Piece>[] al = null;

ArrayList <ArrayList><Piece>> al2 = new ArrayList <ArrayList><Piece>>();

for (int i = 0; i < nPieces; ++i) {

al2.add (new ArrayList<Piece>());

}

// warning "[unchecked]" unchecked cast

return (ArrayList<Piece>[])al2.toArray();

}

public static void main(String[] args) {

TestArrayList tal = new TestArrayList();

ArrayList<Piece> pieces = tal.test(); // compiles OK

ArrayList<Piece>[] pieces2 = tal.test4(10);

}

}

edsonwa at 2007-7-13 2:27:46 > top of Java-index,Core,Core APIs...
# 2
Oh my, not very elegant but it seems to work.Should I report this as a bug?
Fylkea at 2007-7-13 2:27:46 > top of Java-index,Core,Core APIs...
# 3
It's not a bug. You can read about the reasons in the JLS 3.0 (Java Language Specification) or in the Generics tutorial.
edsonwa at 2007-7-13 2:27:46 > top of Java-index,Core,Core APIs...
# 4
Hmm, okay. Well given how much I understood from the Generics tutorial I guess there will be a while before I fully understand this.Thanks for the help.
Fylkea at 2007-7-13 2:27:46 > top of Java-index,Core,Core APIs...