开发者

Objects in ArrayList not retaining their type using generics

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜