大家好,又见面了,我是你们的朋友全栈君。
本文为大家分享了有序集合List中的四种遍历方式,希望能对大家有所帮助。
(学习视频分享:java课程)
先创建一个Student类,用来创建对象,并提供有参和无参构造方法。package lesson1;
public class Student {
String name;
int 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;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
}
以下是四种遍历package lesson1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
//使用学生类创建四个对象,并给对象中的属性赋初值
Student s1 = new Student(“zhangsan1”,20);
Student s2 = new Student(“zhangsan2”,21);
Student s3 = new Student(“zhangsan3”,22);
Student s4 = new Student(“zhangsan4”,23);
//创建一个集合
List studentList = new ArrayList();
//将上面的四个学生对象添加到集合中
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
// 普通for循环遍历
//for (int i = 0 ; i < studentList.size() ; i++) {
//Student s = (Student)studentList.get(i);
//System.out.println(s.getName());
//System.out.println(s.getAge());
//}
//增强for循环遍历
for (Object os:studentList) {
Student s = (Student)os;
System.out.println(s.getName());
System.out.println(s.getAge());
}
//迭代器遍历
//Iterator it = studentList.iterator();
//while (it.hasNext()) {
//Student s = (Student)it.next();
//System.out.println(s.getName());
//System.out.println(s.getAge());
//}
//jdk 1.8版本提供的forEach()方法遍历,这种方法了解就行
//studentList.forEach((os)->{
//Student s = (Student)os;
//System.out.println(s.getName());
//System.out.println(s.getAge());
//});
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/129309.html原文链接:https://javaforall.cn