package com.lesson_13;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
//创建List集合对象
List<Student> list = new ArrayList<>();
Student s1 = new Student("张三丰1", 31);
Student s2 = new Student("张三丰2", 32);
Student s3 = new Student("张三丰3", 33);
//把学生添加到集合
list.add(s1);
list.add(s2);
list.add(s3);
//迭代器:集合特有的遍历方式
Iterator<Student> it = list.iterator();
while(it.hasNext()) {
Student s = it.next();
System.out.println(s.getName());
}
System.out.println("----------");
//普通for:带有索引的遍历方式
for(int i=0; i<list.size();i++) {
Student s = list.get(i);
System.out.println(s.getName());
}
System.out.println("----------");
//增强for:最方便的遍历方式
for(Student s : list) {
System.out.println(s.getName());
}
System.out.println("----------");
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("hello");
linkedList.add("world");
linkedList.add("java");
for(String s:linkedList) {
System.out.println(s);
}
//剩下两种遍历方式大家补齐
}
}
还有一个ArrayList
package com.lesson_17;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.lesson_13.Student;
public class ArrayListDemo {
public static void main(String[] args) {
//创建ArrayList集合对象
ArrayList<Student> array = new ArrayList<>();
//创建学生对象
Student s1 = new Student("张三丰1", 31);
Student s2 = new Student("张三丰2", 32);
Student s3 = new Student("张三丰3", 33);
//把学生添加到集合
array.add(s1);
array.add(s2);
array.add(s3);
//迭代器:集合特有的遍历方式
Iterator<Student> it = array.iterator();
while(it.hasNext()) {
Student s = it.next();
System.out.println(s.getName());
}
System.out.println("----------");
//普通for:带有索引的遍历方式
for(int i=0; i<array.size();i++) {
Student s = array.get(i);
System.out.println(s.getName());
}
//增强for:最方便的遍历方式
for(Student s : array) {
System.out.println(s.getName());
}
}
}
下面是Student类
package com.lesson_13;
public class Student {
private String name;
private int age;
public Student() {
}
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;
}
}
本文通过具体的Java代码示例介绍了如何使用不同方法遍历List集合,包括ArrayList和LinkedList,并展示了迭代器、普通for循环及增强for循环的用法。
609

被折叠的 条评论
为什么被折叠?



