案例:List集合存储学生对象并遍历
public class ListDemo { public static void main(String[] args) { //创建List集合对象 List<Student> list = new ArrayList<Student>(); //创建学生对象 Student s1 = new Student("歪比歪比", 30); Student s2 = new Student("阿巴阿巴", 20); Student s3 = new Student("芜湖起飞", 66); //将学生对象添加到集合 list.add(s1); list.add(s2); list.add(s3); //遍历集合,(迭代器) Iterator<Student> it = list.iterator(); while (it.hasNext()) { Student s = it.next(); System.out.println(s.getName() + "," + s.getAge()); } System.out.println("--------"); //遍历集合,(for循环) for (int i = 0; i < list.size(); i++) { Student s = list.get(i); System.out.println(s.getName() + "," + s.getAge()); } } }
运行结果:
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。