import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test4 {
public static void main(String[] args) {
//创建一个集合,存储Person对象,至少三个,迭代元素,拿出每个人的姓名,
// 并打印!
Collection list = new ArrayList();
Person p = new Person("黄磊",34);
Person p2 = new Person("陆毅",34);
Person p3 = new Person("吴镇宇",54);
list.add(p);
list.add(p2);
list.add(p3);
list.add("abcd");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
if(next instanceof Person){//判断是否是Person类型
String name = ((Person)next).getName();
System.out.println(name);
}
// 简化
// Object next = iterator.next();
// if(next instanceof Person){
// Person thisPerson = (Person)next;
// System.out.println(thisPerson.getName());
// }
}
}
|
|