分析以下需求使用java并完成代码 使用ArrayList集合存储三个学生对象姓名年龄使用四种方式遍历集合打印对象属性
需求分析:
- 需要定义一个学生类,包含姓名和年龄属性。
- 需要使用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
``
原文地址: https://www.cveoy.top/t/topic/cwZm 著作权归作者所有。请勿转载和采集!