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

创建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());

}

}

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章