如何随机使用 ArrayMap
How to use a ArrayMap randomly
我写了下面的ArrayMap:
ArrayMap<Sprite,String> arrayMap = new ArrayMap<Sprite, String>();
arrayMap.put(sprite, "Rot");
arrayMap.put(sprite1, "Braun");
arrayMap.put(sprite2, "Dunkelblau");
arrayMap.put(sprite3, "Dunkelgrün");
arrayMap.put(sprite4, "Gelb");
arrayMap.put(sprite5, "Hellblau");
arrayMap.put(sprite6, "Hellgrün");
arrayMap.put(sprite7, "Lila");
arrayMap.put(sprite8, "Orange");
arrayMap.put(sprite9, "Rosa");
现在我想在设备的屏幕上随机显示其中的四个精灵。但是,我不知道如何使用 ArrayMap 并决定(随机地)绘制哪些精灵。我希望有人能帮助我。
试试下面的代码
Random rand = something
int randIndex = rand.nextInt(list.size());
K key = list.get(randIndex);
V value = map.get(key);
关于何时使用 ArrayMap 根据 android 文档:
Note that this implementation is not intended to be appropriate for
data structures that may contain large numbers of items. It is
generally slower than a traditional HashMap, since lookups require a
binary search and adds and removes require inserting and deleting
entries in the array. For containers holding up to hundreds of items,
the performance difference is not significant, less than 50%.
使用Collections.shuffle()
:
ArrayList<Sprite> keys = new ArrayList(arrayMap.keySet());
Collections.shuffle(keys);
for (int i = 0; i < 4; i++) {
Sprite key = keys.get(i);
String value = arrayMap.get(key);
}
我写了下面的ArrayMap:
ArrayMap<Sprite,String> arrayMap = new ArrayMap<Sprite, String>();
arrayMap.put(sprite, "Rot");
arrayMap.put(sprite1, "Braun");
arrayMap.put(sprite2, "Dunkelblau");
arrayMap.put(sprite3, "Dunkelgrün");
arrayMap.put(sprite4, "Gelb");
arrayMap.put(sprite5, "Hellblau");
arrayMap.put(sprite6, "Hellgrün");
arrayMap.put(sprite7, "Lila");
arrayMap.put(sprite8, "Orange");
arrayMap.put(sprite9, "Rosa");
现在我想在设备的屏幕上随机显示其中的四个精灵。但是,我不知道如何使用 ArrayMap 并决定(随机地)绘制哪些精灵。我希望有人能帮助我。
试试下面的代码
Random rand = something
int randIndex = rand.nextInt(list.size());
K key = list.get(randIndex);
V value = map.get(key);
关于何时使用 ArrayMap 根据 android 文档:
Note that this implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.
使用Collections.shuffle()
:
ArrayList<Sprite> keys = new ArrayList(arrayMap.keySet());
Collections.shuffle(keys);
for (int i = 0; i < 4; i++) {
Sprite key = keys.get(i);
String value = arrayMap.get(key);
}