Reputation: 301
Is there a way to combine Lists and Arrays in Java? I am storing data for a tile map in 2D arrays instead of 2D lists, because that way I can define a set size for them. Its worked so far because each location has a single tile and can only have a single object occupying it. Now I want to add multiple effects to a single tile, but Java does not allow creation of an Array with generics, so no ArrayList[][]. If each tile was its own object it could just have its own ArrayList of effects, but I really want to avoid that. Also I don't know how many effects each tile may have, so I cannot just define a 3D array.
Any suggestions about how to get around this. I would like more design oriented suggestions, instead of a hack to get around the array/generics issue.
Upvotes: 0
Views: 162
Reputation: 309008
I think a more object-oriented approach would suit you better than complex, nested structures.
Encapsulate what you want into a single object that you can maintain in something simpler. I see your approach becoming obtuse and hard to follow rather quickly.
You could maintain a single List
of sparse entries if each one kept its (i, j)
position in the grid along with its state.
Upvotes: 6
Reputation: 22989
The object-oriented way is to make each tile an object, but you say you really want to avoid that. You can use inheritance instead of composition if that's the problem:
class Effects extends ArrayList<Effect> { }
The alternative is to use an unchecked cast, which you also say you don't want:
ArrayList<Effect>[][] board = (ArrayList<Effect>[][]) new ArrayList[...][...];
Upvotes: 1