使用三种不同循环遍历List<Student>
请使用多种不同的方式遍历 学生对象集合
- 传统 for 循环
- 迭代器Iterator
- 增强for循环 底层基于迭代器Iterator
示例代码:
Student.java
java
package com.collection.Demo04;
public class Student {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
}
Test07.java
java
package com.collection.Demo04;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 传统 for 循环
* 迭代器Iterator
* 增强for循环 底层基于迭代器Iterator
*/
public class Test07 {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student("name1", 32));
students.add(new Student("name2", 21));
students.add(new Student("name3", 23));
//方式1------传统 for循环 遍历集合
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
System.out.println(student.getName() + "," + student.getAge());
}
//方式2------ 迭代器遍历集合
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getName() + "," + student.getAge());
}
//方式3------ 增强for循环 for each
for (Student student : students) {
System.out.println(student.getName() + "," + student.getAge());
}
}
}
下一篇文章: