【发布时间】:2014-10-23 16:03:03
【问题描述】:
我要完成的任务是为 1,000,000 个元素的 ArrayList 的每个元素设置一个从 0 到 1000 的随机整数。我使用简单的for loops 成功完成了它,但现在我想通过ListIterator 及其set() 方法获得这个。
static int i = 0;
public static void main(String[] args) {
List rInt = new ArrayList();
for (int i = 0; i <= 1000; i++) {
rInt.add(i);
}
List hMSAL = new ArrayList();
for (int i = 1; i <= 1000000; i++) {
hMSAL.add(i);
}
ListIterator<Integer> gI = hMSAL.listIterator();
while (gI.hasNext()) {
Collections.shuffle(rInt);
int rand = (int) rInt.get(333);
gI.next();
gI.set(rand);
int f = gI.next();
System.out.println(++i + " " + f);
}
问题在于输出。
Output:
1 2
2 4
3 6
4 8
5 10 ...
问:我应该在我的代码中修改什么,所以对于从 1 到 1,000,000 的每个 i,分配的值将是从 1 到 1000 的随机整数。 p>
【问题讨论】:
-
你在循环中调用了 next() 两次。你不应该。此外,您的随机生成速度非常慢。为什么每次迭代都要打乱一个列表。 random.nextInt(1000) 有什么问题?
-
不相关的代码审查:不要使用原始类型。使用
List<Integer>和ArrayList<>。此外,为了清楚起见,您可以将1000000写为1_000_000。
标签: java random arraylist iterator listiterator