get multiple random values from ArrayList HashMap

2019-03-06 04:25发布

问题:

I want to get some specific number random values from ArrayList

final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

for (int i = 0; i == 4; i++) {

        index = random.nextInt(menuItems.size());
        HashMap<String, String> getitem = menuItems.get(index);
        System.out.println(getitem.get(KEY_NAME));
    }

Nothing is printing out.

Code in loop works if i use it outside loop, but since i need multiple values, i use loop and it doesnt work.

回答1:

change

for (int i = 0; i == 4; i++) { // start with i beeing 0, execute while i is 4
                               // never true

to

for (int i = 0; i < 4; i++) {  // start with i beeing 0, execute while i is
                               // smaller than 4, true 4 times

Explanation:

A for loop has the following structure:

for (initialization; condition; update)

initialization is executed once before the loop starts. condition is checked before each iteration of the loop and update is executed after every iteration.

Your initialization was int i = 0; (executed once). Your condition was i == 4, which is false, because i is 0. So the condition is false, and the loop is skipped.



回答2:

The ending condition of your for loop is broken: for (int i = 0; i == 4; i++) should be for (int i = 0; i < 4; i++) (4 iterations) or for (int i = 0; i <= 4; i++) (5 iterations).

This tutorial explains how the for statement works.