从 ArrayList HashMap 获取多个随机值 [英] get multiple random values from ArrayList HashMap
问题描述
我想从 ArrayList 中获取一些特定数字的随机值
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));
}
什么都没有打印出来.
如果我在循环外使用它,循环中的代码可以工作,但是由于我需要多个值,我使用循环并且它不起作用.
Code in loop works if i use it outside loop, but since i need multiple values, i use loop and it doesnt work.
推荐答案
change
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 循环具有以下结构:
Explanation:
A for loop has the following structure:
for (initialization; condition; update)
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.
您的初始化是 int i = 0;
(执行一次).您的条件是 i == 4
,这是错误的,因为 i
是 0
.所以条件为假,跳过循环.
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.
这篇关于从 ArrayList HashMap 获取多个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!