三種方式遍歷ArrayList


package com.Test01;

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

public class ArrayListDemo {
public static void main(String[] args) {
//創建ArrayList集合對象
ArrayList<Student> array = new ArrayList<Student>();

//創建學生對象 提前定義學生類
Student s1 = new Student("王五",20);
Student s2 = new Student("張五",21);
Student s3 = new Student("李五",22);

//添加學生對象到集合中

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()+","+s.getAge());
}
System.out.println("------------------------");

//普通for遍歷,帶有索引
for(int i = 0;i<array.size();i++) {
Student s = array.get(i);
System.out.println(s.getName()+","+s.getAge());
}
System.out.println("-----------------------");

//增強for遍歷
for(Student s : array) {
System.out.println(s.getName()+","+s.getAge());
}

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM