Insanovation
Insanovation

Reputation: 345

Set an integer using ListIterator

The task I want to accomplish is to set a random int from 0 to 1000, for each element of an ArrayList of 1,000,000 elements. I did it successfully using simple for loops, but now I want to obtain this trough the ListIterator and its set() method.

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);
        }

The problem is the output.

Output: 

1 2

2 4

3 6

4 8

5 10 ...

Q: What should I modify in my code, so for each i from 1 to 1,000,000 the assigned value would be a random integer from 1 to 1000.

Upvotes: 0

Views: 417

Answers (1)

ifloop
ifloop

Reputation: 8386

I don't now if I got you right, but try this:

Change

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

To

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

If this doesn't result in the desired output, please clarify your question.

Upvotes: 1

Related Questions