Unknown
Unknown

Reputation: 21

How to shuffle in same order?

I have two ArrayList, the one is a Bitmap typ and contains picture and the other is a String which contains the text for the bitmap.

I just want to shuffle the Bitmap, but the String ArrayList should be in the same order.

private ArrayList<Bitmap> tmpBitmap = new ArrayList<Bitmap>();
private ArrayList<String> tmpName = new ArrayList<String>();

I tried this, but it shuffles in different orders.

Collections.shuffle(tmpWord);
Collections.shuffle(tmpName);

Upvotes: 0

Views: 883

Answers (3)

hedgecrab
hedgecrab

Reputation: 21

long seed = new Random().nextLong();
Collections.shuffle(tmpWord, new Random(seed));
Collections.shuffle(tmpName, new Random(seed));

Upvotes: 2

khelwood
khelwood

Reputation: 59096

I said in the comments that you would be better off putting the strings and bitmaps into objects together so you don't need to maintain parallel lists. Here is basically how that would be:

class NamedBitmap {
    String name;
    Bitmap bitmap;
    // use privacy modifiers and accessors according to your taste
    public NamedBitmap(String name, Bitmap bitmap) {
        this.name = name;
        this.bitmap = bitmap;
    }
}

List<NamedBitmap> namedBitmaps = new ArrayList<NamedBitmap>();

...

Collections.shuffle(namedBitmaps);

This way the names are always tied to the bitmaps; you don't have to keep two lists in the same order to keep them associated.

Parallel arrays (or lists) are how people had to associate related data in a time before structs and objects provided better options.

Edit:

Given a List<NamedBitmap> namedBitmaps as described above, you can add stuff into it using:

namedBitmaps.add(new NamedBitmap(givenName, givenBitmap));

and you can access the names and bitmaps using namedBitmaps.get(i).name and namedBitmaps.get(i).bitmap.

Upvotes: 4

Dave Gordon
Dave Gordon

Reputation: 1835

Change your two ArrayLists to a Map<Bitmap,string> collection then when you shuffle you get both shuffled as you expect and only have to access one collection to get all the information you need. Although this does require that the bitmaps are unique

*Thanks to kcoppock for noticing it was Android / Java

Upvotes: 2

Related Questions