I have the following test code. I'm trying to understand the interoperability between Generics and legacy.
List myList = new ArrayList();
myList.add("abc");
myList.add(1);
myList.add(new Object());
System.out.println("Printing the unchecked list");
Iterator iterator = myList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
List<String> strings = myList;
System.out.println("Printing the unchecked list assigned to List<String> using iterator");
Iterator stringIterator = strings.iterator();
while (stringIterator.hasNext()) {
System.out.println(stringIterator.next()); // this works fine! why? shouldn't it fail converting the 1 (int/Integer) to String?
}
System.out.println("Printing the unchecked list assigned to List<String> using for");
for (int i = 0; i != strings.size(); i++) {
System.out.println(strings.get(i)); // blows up as expected in the second element, why?
}
System.out.println("Printing the unchecked list assigned to List<String> using foreach");
for (String s : strings) {
System.out.println(s); // blows up as expected in the second element, why?
}
Why does the iterator.next
work fine when I try to print it while the System.out.println
blows up as expected when I iterate using for
loops?