I have a two-dimensional ArrayList
to store Block
objects to use later. However, it won't let me call Block
methods on the objects when I get them by their index in the list. Here is the code where I initialize the list:
ArrayList<ArrayList> col = new ArrayList<ArrayList>();
for(int column = 0; column < SIZE; column++) {
// Add a row of block objects
col.add(new ArrayList<Block>());
// Populate the row
开发者_开发技巧 for(int row = 0; row < SIZE; row++) {
col.get(column).add(new Block());
grid.add((Block) col.get(column).get(row));
}
}
The problem seems to be that when I go to add the block to the grid
(a JPanel), it won't compile unless I cast the object back to a Block
. In other words, grid.add(col.get(column).get(row))
won't work. Any ideas why this might be happening?
You need it to be
ArrayList<ArrayList<Block>> col = new ArrayList<ArrayList<Block>>();
When you have just ArrayList<ArrayList>
the get's would look like this
ArrayList<ArrayList> col = new ArrayList<ArrayList>();
ArrayList list = col.get(i);
Object obj = list.get(j);
Since list
is an ArrayList with no type it will always return an Object.
If you have it as ArrayList<ArrayList<Block>>
it would look like
ArrayList<ArrayList<Block>> col = new ArrayList<ArrayList<Block>>();
ArrayList<Block> list = col.get(i);
Block obj = list.get(j);
精彩评论