You have to separate this into two steps:
- Create the map you want to insert.
- Insert it into
mapSnakes.
Like this:
if(mGameAssets[i].getAssetType().isSnake()){ //check if the asset is snake
// Step 1
Map<Integer,Integer> assetMap = new HashMap<Integer,Integer>();
assetMap.put(i, mGameAssets[i].getDamage());
// Step 2
mapSnakes.put(++coutner, assetMap);
}
Although your design looks a little odd, are you sure this is what you want to be doing?
Responding to your comment, you say you want to know two things:
- How many snakes are in
mGameAsset.
- What indices they are and what their damage is.
You could use a single map for that, a map that maps indices to the snake itself, e.g. assuming your assets are of class Asset:
private void filterSnakes () {
// maps asset index => snake
Map<Integer,Asset> snakes = new HashMap<Integer,Asset>();
// find all the snakes:
for (int i = 0; i < mGameAssets.length; ++ i) {
if (mGameAssets[i].getAssetType().isSnake())
snakes.put(i, mGameAssets[i]);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// now we can process their indices and damage, for example:
for (Map.Entry<Integer,Asset> snakeEntry : snakes.entrySet()) {
int index = snakeEntry.getKey();
int damage = snakeEntry.getValue().getDamage();
System.out.println("Snake at " + index + " damage is " + damage);
}
// and we can find the number of snakes too:
int snakeCount = snakes.size();
System.out.println("There are " + snakeCount + " snakes.");
// bonus: we can even just get a generic collection of the snakes:
Collection<Asset> snakesOnly = snakes.values();
}
Use a LinkedHashMap if you want to preserve insertion order instead.
Another option is to use an ArrayList or some other List instead of a Map; if you do that you'll have to make some small class that can hold an index and a snake (similar to a Map.Entry<Integer,Asset>, then you can create one of those small classes for each snake entry and maintain a List of those. A bit more work but has the advantage of not having the overhead of a map (which may or may not matter to you).