Java ArrayList 遍历集合四种方式:实例代码讲解
Java ArrayList 遍历集合四种方式:实例代码讲解
本教程将通过实例代码演示如何使用 Java ArrayList 集合存储学生对象,并使用四种方式进行遍历,包括:
- 迭代器 (Iterator)
- ListIterator
- 普通 for 循环
- 增强 for 循环
需求分析
- 需要定义一个学生类
Student,包含姓名和年龄属性。 - 需要使用
ArrayList集合存储三个学生对象。 - 需要使用四种方式遍历集合,打印每个学生对象的属性。
代码实现
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// 创建三个学生对象并添加到ArrayList集合中
List<Student> list = new ArrayList<>();
list.add(new Student('张三', 18));
list.add(new Student('李四', 19));
list.add(new Student('王五', 20));
// 使用迭代器遍历集合
System.out.println('使用迭代器遍历集合:');
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getName() + ' ' + student.getAge());
}
// 使用ListIterator遍历集合
System.out.println('使用ListIterator遍历集合:');
ListIterator<Student> listIterator = list.listIterator();
while (listIterator.hasNext()) {
Student student = listIterator.next();
System.out.println(student.getName() + ' ' + student.getAge());
}
// 使用for循环遍历集合
System.out.println('使用for循环遍历集合:');
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
System.out.println(student.getName() + ' ' + student.getAge());
}
// 使用增强for循环遍历集合
System.out.println('使用增强for循环遍历集合:');
for (Student student : list) {
System.out.println(student.getName() + ' ' + student.getAge());
}
}
}
输出结果
使用迭代器遍历集合:
张三 18
李四 19
王五 20
使用ListIterator遍历集合:
张三 18
李四 19
王五 20
使用for循环遍历集合:
张三 18
李四 19
王五 20
使用增强for循环遍历集合:
张三 18
李四 19
王五 20
总结
本教程详细介绍了使用 Java ArrayList 集合存储学生对象并使用四种方式进行遍历。你可以根据自己的实际需求选择最合适的方式。
注意: 为了提高代码的可读性,建议使用增强 for 循环,因为它更加简洁易懂。
原文地址: https://www.cveoy.top/t/topic/nwSf 著作权归作者所有。请勿转载和采集!