import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
* 使用迭代器来遍历单列集合!
* 1、遍历字符串
* 2、遍历自定义对象Student
*
* 大家练习:
* 需求:
1:首先定义一个标准学生类(name,age属性)
2:用集合存储3个学生,然后遍历集合。打印出每个学生的name和age。
*/
public class Demo2 {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
Student s1 = new Student(20, "李小龙");
Student s2 = new Student(30, "叶问");
Student s3 = new Student(50, "周星驰");
c.add(s1);
c.add(s2);
c.add(s3);
//Collection : Iterator iterator();
Iterator it = c.iterator();
while(it.hasNext()){
Object obj = it.next();//多态
Student s = (Student) obj;
System.out.println(s.getName() + "..." + s.getAge());
}
/*Collection c = new ArrayList();
c.add("a");
c.add("b");
c.add("c");
Iterator it = c.iterator();//获取迭代器
while(it.hasNext()){//判断有没有下一个元素,如果有就返回true,否则就返回false
System.out.println(it.next());//取下一个元素
}*/
/*Iterator it = c.iterator();//获取迭代器
boolean b1 = it.hasNext();
System.out.println(b1);
System.out.println(it.next());
System.out.println(it.hasNext());
System.out.println(it.next());
System.out.println(it.hasNext());
System.out.println(it.next());
System.out.println(it.hasNext());
System.out.println(it.next());*/
//Iterator iterator();
/*Iterator it = c.iterator();//获取迭代器
Object o1 = it.next();
System.out.println(o1);
Object o2 = it.next();
System.out.println(o2);
Object o3 = it.next();
System.out.println(o3);
System.out.println(it.next());*/
}
}
class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
public Student() {
super();
}
}
|
|