您對此分成兩個步驟:
- 創建要插入地圖。
- 將其插入
mapSnakes
。
像這樣:
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);
}
雖然你的設計看起來有點奇怪,你確定這是你想要做什麼?
響應您的評論,你說你想知道兩件事情:
- 多少蛇是在
mGameAsset
。
- 他們是什麼指數和他們的損害是什麼。
您可以使用單個地圖來繪製地圖,該地圖將索引映射到蛇本身,例如,假設你的資產是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();
}
,如果你想保留插入順序,而不是使用LinkedHashMap
。
另一種選擇是使用ArrayList
或其他List
而不是Map
;如果你這樣做,你將不得不做一些可以容納索引和蛇的小類(類似於Map.Entry<Integer,Asset>
,那麼你可以爲每個蛇入口創建一個小類,並保留這些類的一個List
。工作,但有沒有一個地圖的開銷(這可能會或可能無所謂你)的優勢
是否有任何理由使用散列表而不是數組,如果你會使用增量數字來索引它? – fejese
@fejese只是簡單的訪問內容我猜。 –