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]

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);
}
}