0

I have a program that prints the ArrayList in java. The ArrayList should retain the order of insertion right?

import java.util.*;

class Generator {
    String[] s = { "snow", "white", "and", "the", "seven", "dwarfs" };

    String s1;

    static int i = 0;

    String next() {
        s1 = s[i];
        i++;
        if (i == s.length) {
            i = 0;
        }
        return s1;
    }

    public static void main(String[] args) {
        Collection<String> al = new ArrayList<String>();
        // Collection<String> ll=new LinkedList<String>();
        Generator g = new Generator();
        for (int i = 0; i < 10; i++) {

            al.add(g.next());
            // ll.add(g.next());
        }

        System.out.println(al);
        // System.out.println(ll);
    }
}

with the LinkedList object stuff commented, I am getting right output

[snow, white, and, the, seven, dwarfs, snow, white, and, the]

but when I uncomment the LinkedList code I am getting output as:

[snow, and, seven, snow, and, seven, snow, and, seven, snow]
[white, the, dwarfs, white, the, dwarfs, white, the, dwarfs, white]

Can anyone please explain me this behavior? I am confused.

1
  • u have to call next() only once inside the loop. So create a local variable for g.next(). then use that variable. Commented Aug 19, 2014 at 13:04

4 Answers 4

2

When you uncomment the linked list, you are calling next() twice in every loop.

The first word is stored in the array list, the second one in the linked list, the third list in the array list...

Next, please!

Sign up to request clarification or add additional context in comments.

Comments

1

You can call like below.

    String next = g.next();
    al.add(next);
    ll.add(next);

Instead of calling next() method two times.

Comments

0

g.next() removes the next item and returns it. So when you uncomment the LinkedList code, your loop removes two items each iteration, and adds one to each list.

Comments

0

if you uncomment linkedList than first value will be inserted in the ArrayList and second value will be inserted in the LinkedList so both list contains alternate vaues and will be printed in alternate order.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.