【问题标题】:Set an integer using ListIterator使用 ListIterator 设置整数
【发布时间】: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&lt;Integer&gt;ArrayList&lt;&gt;。此外,为了清楚起见,您可以将1000000 写为1_000_000

标签: java random arraylist iterator listiterator


【解决方案1】:

如果我没听错的话,我现在不知道,但试试这个:

改变

// ...
gI.next();
gI.set(rand);
int f = gI.next();
// ...

// ...
Integer f = gI.next();
gI.set(rand);
// ...

如果这没有产生所需的输出,请澄清您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2011-02-20
    • 1970-01-01
    • 2019-12-23
    • 2012-01-19
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多