public class Stage2Clone {
public static void main(String[] args) {
ArrayList stringList = new ArrayList();
stringList.add(new Employee(1,"A"));
stringList.add(new Employee(2,"j"));
stringList.add(new Employee(3,"d"));
stringList.add("Hello");
stringList.add(new String("Abc"));
stringList.add(10);
stringList.add(new Integer(100));
System.out.println(stringList);
m1(stringList);
m2(stringList);
}
public static void m1(ArrayList<Employee> al){
Iterator<Employee> iterator = al.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
public static void m2(ArrayList<String> al){
Iterator<String> iterator = al.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Run Code Online (Sandbox Code Playgroud)
那不是迭代器问题,而是破坏代码的 System.out.println。在运行时,集合中没有类型检查(查找泛型的类型擦除以获取详细信息)
您的代码失败,因为在 m1 中您实际上正在调用
System.out.println(Object ob)
所以这一切都会被打印出来,因为你收藏中的每一件东西都是一个 Object
但是在 m2 调用中System.out.println(String str)
,这是执行的类型检查,除了String此方法之外,您不能传递对象