Iterator和foreach;
先给Student类:
package com.xuyigang1234.chp06.sec01; public class Student { private String name; private int age; 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 com.xuyigang1234.chp06.sec01; import java.util.Iterator; import java.util.LinkedList; public class TestIterator { public static void main(String[] args) { LinkedList<Student> list = new LinkedList<Student>(); list.add(new Student("小白",10)); list.add(new Student("小红",14)); list.add(new Student("小黑",12)); //用Iterator遍历 Iterator<Student> it = list.iterator(); //返回迭代器 while(it.hasNext()) { Student s=it.next(); //返回迭代的下一个元素 System.out.println("姓名:"+s.getName()+",年龄:"+s.getAge()); } System.out.println("----------------------------"); //用 foreach遍历 for(Student s:list) { System.out.println("姓名:"+s.getName()+",年龄:"+s.getAge()); } } }
姓名:小白,年龄:10 姓名:小红,年龄:14 姓名:小黑,年龄:12 ---------------------------- 姓名:小白,年龄:10 姓名:小红,年龄:14 姓名:小黑,年龄:12