1. 程式人生 > 其它 >List三種遍歷集合方式

List三種遍歷集合方式

package com.czie.iot1913.lps.List;

/**
* @author [email protected]
* @date 2022-03-17 14:05
*/
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;
}
}


package com.czie.iot1913.lps.List;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* @author [email protected]
* @date 2022-03-17 17:29
*/
public class StudentListTest {
public static void main(String[] args) {
Student s1 = new Student("劉品水",21);
Student s2 = new Student("劉呂水",22);
Student s3 = new Student("劉口水",23);
List<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
//增強for遍歷
for (Student s01:list){
System.out.println(s01.getName()+","+s01.getAge());
}
System.out.println("=======");
//Iterator遍歷
Iterator<Student> it = list.iterator();
while (it.hasNext()){
Student s02=it.next();
System.out.println(s02.getName()+","+s02.getAge());
}
System.out.println("=======");
//for迴圈遍歷
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName()+","+list.get(i).getAge());
}

}
}