有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java泛型与遗留代码的兼容性为什么foreach在运行时失败,而迭代器工作正常

我有以下测试代码。我试图理解泛型和遗留系统之间的互操作性

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?
}

为什么当我尝试打印iterator.nextSystem.out.println运行良好,而当我使用for循环进行迭代时System.out.println会像预期的那样崩溃


共 (0) 个答案