0

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.

1
  • would this help u? -> List<List<>> Commented Jun 8, 2013 at 3:06

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 think about the API for both options. The array/list would be a mess and you'd lose weeks of your life debugging it. A cleaner OO approach would let you get on with the real work. Internally it may use arrays or lists or whatever, but the interface would conceal that complexity
BTW having something like HashMap<Pair<int, int>, List<Item>> instead of a plain list of entries can make per-cell lookup very efficient even if a serious number of cells contain items and scanning a list becomes impractical.
If the List is sparse it'll be more efficient than your proposal. And I don't see how yours is significantly different from mine, except that I encapsulate the position in the Item.
1

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[...][...];

Comments

1

Powerful Guava Table (JavaDoc) can be used.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.