package cn.itcast_02;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.plaf.synth.SynthSeparatorUI;
/*
*
* ArrayList存储自定义对象
*
*/
public class ArrayList存储自定义对象 {
public static <E> void main(String[] args) {
//创建集合对象
ArrayList array = new ArrayList();
//创建学生对象
Student s1 = new Student("武松",25);
Student s2 = new Student("林冲",35);
Student s3 = new Student("杨志",34);
Student s4 = new Student("天道",25);
//添加元素
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());
}
for(int x=0;x<array.size();x++) {
Student s = (Student)array.get(x);
System.out.println(s.getName()+"-------"+s.getAge());
}
}
}
ArrayList存储自定义对象
最新推荐文章于 2024-12-10 11:48:01 发布
本文演示了如何使用Java的ArrayList来存储自定义对象,通过创建学生对象并将其添加到ArrayList中,然后使用迭代器和for循环进行遍历和打印。
1566

被折叠的 条评论
为什么被折叠?



