ArrayList和Iterator的初步使用(一)

时间:2021-07-05 17:08:55
package cn.cp;
//ArrayList和Iterator的初步使用(一)
//注意:Person p = (Person) iterator.next();// 为什么取出来要转型?
//因为没有使用泛型,扔进去以后都成了Object,所以再取时转型
//
import java.util.ArrayList;
import java.util.Iterator;

class Person {
private int age;
private String name;

public Person(int age, String name) {
super();
this.age = age;
this.name = 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;
}

@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}

}

public class ArrayListTest1 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new Person(11, "bbba"));
arrayList.add(new Person(22, "aaaa"));
arrayList.add(new Person(44, "uuul"));
arrayList.add(new Person(99, "wwww"));
arrayList.add(new Person(88, "xxxx"));
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()) {
Person p = (Person) iterator.next();// 为什么取出来要转型?因为没有使用泛型,扔进去以后都成了Object
if (p.getAge() > 11) {
System.out.println(p.toString());
}
}
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
for(int x=0;x<arrayList.size();x++){//输出了ArrayList的每个对象的信息,实际是调用了toString
System.out.println(arrayList.get(x));
}
}
}