0

I wrote the following 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");

Now I want to show randomly four of these sprites on a screen of a device. However, I don´t know how to use the ArrayMap and decide (randomly) which sprites will be drawn. I hope somebody can help me.

user8340536
  • 209
  • 2
  • 7

2 Answers2

0

try this code below

Random rand = something
int randIndex = rand.nextInt(list.size());
K key = list.get(randIndex);
V value = map.get(key);
6155031
  • 4,171
  • 6
  • 27
  • 56
0

About when to use ArrayMap according to android documentation:

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%.

Using 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);
    }
Fatih Santalu
  • 4,641
  • 2
  • 17
  • 34
  • If I type that in, keySet is red. Error Message: "Cannot resolve method ´keySet()´. – user8340536 Jul 28 '17 at 14:39
  • I suspect you're using a LibGDX `ArrayMap` rather than the Android one: https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/ArrayMap.html. In which case, instead of `arrayMap.keySet()` use `arrayMap.keys()` – JK Ly Jul 28 '17 at 17:28