先建立一个学生类
package ysy09;
public class Student {
private String name;
private int age ;
public Student() {
}
public Student(String name, int age) {
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 ysy09;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
//创建List集合对象
List<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("小胖", 12);
Student s2 = new Student("小爱", 13);
Student s3 = new Student("小鱼", 15);
//把学生添加到集合
c.add(s1);
c.add(s2);
c.add(s3);
//迭代器遍历:集合特有的遍历方式
Iterator <Student> it = c.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.getName()+","+s.getAge());
}
System.out.println("-------------");
//普通for遍历:带有索引的遍历方式
for (int i = 0; i < c.size(); i++) {
Student s = c.get(i);
System.out.println(s.getName()+","+s.getAge());
}
System.out.println("-------------");
//增强for遍历:最方便的遍历方式
for (Student s:c){
System.out.println(s.getName()+","+s.getAge());
}
}
}
版权声明:本文为weixin_43945903原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。