需求:ArrayList存储自定义对象并遍历。要求加入泛型,并用增强for遍历。
A:迭代器
B:普通for
C:增强for
LinkedList,Vector,Colleciton,List等存储继续练习
增强for是用来替迭代器。
1 package cn_JDK5new; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 7 public class ArrListDemo2 { 8 public static void main(String[] args) { 9 //创建集合 注意:这里是存储自定义对象,则类型里要填那个对象的类名 10 ArrayList<Person> alt = new ArrayList<Person>(); 11 12 //创建自定义对象 13 Person s1 = new Person("阿猫","女",20); 14 Person s2 = new Person("阿狗","男",22); 15 Person s3 = new Person("张三","男",19); 16 Person s4 = new Person("阿拉尔","女",20); 17 18 //添加元素到集合 19 alt.add(s1); 20 alt.add(s2); 21 alt.add(s3); 22 alt.add(s4); 23 24 //遍历 25 //迭代器 26 Iterator<Person> it = alt.iterator(); 27 while(it.hasNext()){ 28 Person p1 = it.next(); 29 System.out.println(p1.getName()+" "+p1.getSex()+" "+p1.getAge()); 30 } 31 System.out.println("------------"); 32 33 //普通for 34 for(int x = 0;x < alt.size(); x++){ 35 Person p2= alt.get(x); 36 System.out.println(p2.getName()+" "+p2.getSex()+" "+p2.getAge()); 37 } 38 System.out.println("------------"); 39 40 //增强for 41 for(Person p3 : alt){ 42 System.out.println(p3.getName()+" "+p3.getSex()+" "+p3.getAge()); 43 } 44 } 45 }