程序1:
public class IteratorDemo {
public static void main(String[] args) {
// 创建对象
Collection c = new ArrayList();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
Iterator it = c.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s);
}
}
}
程序2:
import ItetatorDemo.Student;
public class ListTest {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList();
//创建元素对象
Student stu1 = new Student("张三",24);
Student stu2 = new Student("李四",26);
Student stu3 = new Student("王五",30);
//将元素对象添加进集合
list.add(stu1);
list.add(stu2);
list.add(stu3);
//方式一
//获取迭代器对象
Iterator it = list.iterator();
while(it.hasNext()){
Object obj =it.next();
Student s = (Student)obj;
System.out.println(s.getName()+"----"+s.getAge());
}
在while(it.hasNext()){}中
程序一用了String s = (String) it.next();
程序2用了Object obj =it.next();
那么这两者有什么区别,分别用在什么情况下?弄不懂了,有没有大神来指教下?
|
|