Java – How to dynamically solve this random button implementation

How to dynamically solve this random button implementation… here is a solution to the problem.

How to dynamically solve this random button implementation

I have a list with integers 0, 1, 2, 3, 4. Then I’m shuffling the cards, and as a third step, I want to initialize the button with the first object related to button1, the second object related to button2, etc.
If I do it manually, it works, but I want to solve it dynamically.

    List<Integer> objects = new ArrayList<Integer>();
            objects.add(0);
            objects.add(1);
            objects.add(2);
            objects.add(3);
            objects.add(4);

 Shuffle the collection
    Collections.shuffle(objects);

this is not working here, but it should reflect what i am trying to achieve here
 -->
    for (int i = 0; i<objects.size(); i++) {
        Button button**i** = (Button)findViewById(R.id.button**i**);
        button**i**.setText(objects.get(i).toString());
    }

Thanks in advance. Any help appreciated (poke my nose in the right direction).

Solution

You can fix this by scrambling the list of buttons. When you iterate with int, it can be used as an index for a shrambled list.

Like this:

List<Button> buttons = new ArrayList<Button>();
buttons.add((Button)findViewById(R.id.button0));
buttons.add((Button)findViewById(R.id.button1));
buttons.add((Button)findViewById(R.id.button2));
buttons.add((Button)findViewById(R.id.button3));
buttons.add((Button)findViewById(R.id.button4));

Collections.shuffle(buttons);

for (int i = 0, s = 4; i < s; i++) {
    buttons.get(i).setText("" + i);
}

Related Problems and Solutions