package Collection_04;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
//需求:请用5种方式遍历List集合
public class ArrayListDemo {
public static void main(String[] args) {
// 创建List集合对象
ArrayList<Student> ls = new ArrayList<Student>();
// 创建元素对象
Student s1 = new Student("王菲", 25, 8899);
Student s2 = new Student("孙露", 24, 3399);
Student s3 = new Student("王者", 23, 6699);
Student s4 = new Student("鲁夫", 27, 4599);
// 存储元素对象
ls.add(s1);
ls.add(s2);
ls.add(s3);
ls.add(s4);
// 遍历元素
// 方式一 采用迭代器
Iterator<Student> it = ls.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.toString());
}
System.out.println("----------------------------");
// 方式二 toarr方法
Object[] oj = ls.toArray();
for (int x = 0; x < oj.length; x++) {
Student s = (Student) oj[x];
System.out.println(s.toString());
}
System.out.println("----------------------------");
// 方式三 普通for遍历
for (int y = 0; y < ls.size(); y++) {
Student s = (Student) ls.get(y);
System.out.println(s.toString());
}
System.out.println("----------------------------");
// 方式四 ListIterator 列表迭代器
ListIterator<Student> li = ls.listIterator();
while (li.hasNext()) {
Student s = (Student) li.next();
System.out.println(s.toString());
}
System.out.println("----------------------------");
// 方式五 for增强
for (Student str : ls) {
System.out.println(str);
}
System.out.println("----------------------------"); |
|