Reputation: 123
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.
Upvotes: 0
Views: 123
Reputation: 93
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.
Upvotes: 0
Reputation: 2006
You can call like below.
String next = g.next();
al.add(next);
ll.add(next);
Instead of calling next() method two times.
Upvotes: 1
Reputation: 4435
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.
Upvotes: 0
Reputation: 24780
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!
Upvotes: 2