您的位置:首页 > 其它

集合框架(ArrayList存储自定义对象并遍历)

2016-04-29 10:08 429 查看
创建student类package cn.itcast_01;
public class Student { private String name; private int age;
public Student() { super(); }
public Student(String name, int age) { super(); this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}

package cn.itcast_01;

import java.util.ArrayList;
import java.util.Iterator;

/*
* ArrayList存储自定义对象并遍历
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// 创建集合对象
ArrayList array = new ArrayList();

// 创建学生对象
Student s1 = new Student("武松", 30);
Student s2 = new Student("鲁智深", 40);
Student s3 = new Student("林冲", 36);
Student s4 = new Student("杨志", 38);

// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);

// 遍历
Iterator it = array.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName() + "---" + s.getAge());
}

System.out.println("----------------");

for (int x = 0; x < array.size(); x++) {
// ClassCastException 注意,千万要搞清楚类型
// String s = (String) array.get(x);的是student类型,却强转String类型,但是这里不报错,为什么?因为这里array.get(x)拿的是object类型,array.get(x)以为它是字符串呢,所以编译不报错,但是运行 ClassCastException错,叫类型转换异常
// System.out.println(s);

Student s = (Student) array.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息