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.