从ArrayList HashMap中获取多个随机值

我想从ArrayList获取一些特定的数字随机值

final ArrayList<HashMap> menuItems = new ArrayList<HashMap>(); for (int i = 0; i == 4; i++) { index = random.nextInt(menuItems.size()); HashMap getitem = menuItems.get(index); System.out.println(getitem.get(KEY_NAME)); } 

什么都没打印出来。

如果我在循环外使用它,循环中的代码工作,但因为我需要多个值,我使用循环,它不起作用。

更改

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

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

说明:

for循环具有以下结构:

 for (initialization; condition; update) 

initialization在循环开始之前执行一次。 在循环的每次迭代之前检查condition并且在每次迭代之后执行update

你的初始化是int i = 0; (执行一次)。 你的条件是i == 4 ,这是假的,因为i0 。 因此条件为假,并且跳过循环。

for循环的结束条件被破坏: for (int i = 0; i == 4; i++)应该是for (int i = 0; i < 4; i++) (4次迭代)或者for (int i = 0; i <= 4; i++) (5次迭代)。

本教程解释了for语句的工作原理。