1. ArrayList存储自定义对象并遍历
2. 代码示例:
Student.java,如下:
1 package cn.itcast_01; 2 3 public class Student { 4 private String name; 5 private int age; 6 7 public Student() { 8 super(); 9 } 10 11 public Student(String name, int age) { 12 super(); 13 this.name = name; 14 this.age = age; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public int getAge() { 26 return age; 27 } 28 29 public void setAge(int age) { 30 this.age = age; 31 } 32 33 }
测试类ArrayListDemo2:
1 package cn.itcast_01; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 /* 7 * ArrayList存储自定义对象并遍历 8 */ 9 public class ArrayListDemo2 { 10 public static void main(String[] args) { 11 // 创建集合对象 12 ArrayList array = new ArrayList(); 13 14 // 创建学生对象 15 Student s1 = new Student("武松", 30); 16 Student s2 = new Student("鲁智深", 40); 17 Student s3 = new Student("林冲", 36); 18 Student s4 = new Student("杨志", 38); 19 20 // 添加元素 21 array.add(s1); 22 array.add(s2); 23 array.add(s3); 24 array.add(s4); 25 26 // 遍历 27 Iterator it = array.iterator(); 28 while (it.hasNext()) { 29 Student s = (Student) it.next(); 30 System.out.println(s.getName() + "---" + s.getAge()); 31 } 32 33 System.out.println("----------------"); 34 35 for (int x = 0; x < array.size(); x++) { 36 // ClassCastException 注意,千万要搞清楚类型 37 // String s = (String) array.get(x); 38 // System.out.println(s); 39 40 Student s = (Student) array.get(x); 41 System.out.println(s.getName() + "---" + s.getAge()); 42 } 43 } 44 }
运行效果如下: