List自定义对象的两种遍历方式

第一部分


//创建学生类
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}

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;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

第二部分
public class StudentArray {
public static void main(String[] args){
//创建集合
ArrayList list = new ArrayList();
//赋值
Student s1 = new Student("小燕子",45);
Student s2 = new Student("刘亦菲",40);
Student s3 = new Student("花千骨",38);
Student s4 = new Student("卓别林",70);
Student s5 = new Student("周润发",65);
//给集合添加元素
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
//迭代遍历
Iterator it = list.iterator();
while(it.hasNext()){
Student s = (Student) it.next();
System.out.println(s.getName()+"---"+s.getAge());
}
//for循环遍历
for(int x=0;x<list.size();x++){
Student s = (Student) list.get(x);
System.out.println(s.getName()+"----"+s.getAge());
}
}
}

猜你喜欢

转载自www.cnblogs.com/WTBK/p/9402759.html