package collection1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class IteratorTest {
/*
* 练习:自定义Person对象,姓名
* 将对象存储到集合中,并取出,获取其姓名或者年龄
* 先要对该对象进行描述
*
* add(Object obj);//可以接收任意类型对象,但是
* 任意类型对象都被提升为了Object
* 所以在取出元素时,取出来的也是Object
* 要进行强转
*/
public static void main(String[] args) {
//创建一个集合
Collection collection=new ArrayList();
Person person=new Person("lisi", 23);
collection.add(person);
collection.add(new Person("wagnwu", 34));
collection.add(new Person("zhaoliu", 30));
Iterator it=collection.iterator();
while(it.hasNext()){//在进行迭代时,next方法在循环中,建议只使用一个,
Object obj=it.next();
Person person2=(Person)obj;
System.out.println(person2.getName()+"...."+person2.getAge());
}
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class IteratorTest {
/*
* 练习:自定义Person对象,姓名
* 将对象存储到集合中,并取出,获取其姓名或者年龄
* 先要对该对象进行描述
*
* add(Object obj);//可以接收任意类型对象,但是
* 任意类型对象都被提升为了Object
* 所以在取出元素时,取出来的也是Object
* 要进行强转
*/
public static void main(String[] args) {
//创建一个集合
Collection collection=new ArrayList();
Person person=new Person("lisi", 23);
collection.add(person);
collection.add(new Person("wagnwu", 34));
collection.add(new Person("zhaoliu", 30));
Iterator it=collection.iterator();
while(it.hasNext()){//在进行迭代时,next方法在循环中,建议只使用一个,
Object obj=it.next();
Person person2=(Person)obj;
System.out.println(person2.getName()+"...."+person2.getAge());
}
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}