【我的Java筆記】ArrayList集合的遍歷巢狀
阿新 • • 發佈:2019-01-25
例子:假設有一個年級,一個年級中存在多個班級,而班級中的每一個學生都是一個物件
ArrayList<Student>表示一個班級,而年級大的集合則可用:ArrayList<ArrayList<Student>>來表示
圖解:
/* * 集合的遍歷巢狀 * 大集合:ArrayList<ArrayList<Football>> * */ import java.util.ArrayList; public class FootballTest { public static void main(String[] args){ //建立ArrayList大集合物件 ArrayList<ArrayList<Football>> Team = new ArrayList<>(); //建立第一個子集合物件ArrayList<Football> ArrayList<Football> team1 = new ArrayList<>(); Football f1 = new Football("伊卡爾迪",24); Football f2 = new Football("坎德雷瓦",27); Football f3 = new Football("佩裡西奇",26); //給第一個子集合中新增元素 team1.add(f1); team1.add(f2); team1.add(f3); //將第一個子集合新增至大集合中 Team.add(team1); ////建立第二個子集合物件ArrayList<Football> ArrayList<Football> team2 = new ArrayList<>(); Football f4 = new Football("塞薩爾",24); Football f5 = new Football("托爾多",27); Football f6 = new Football("漢達諾維奇",26); //給第二個子集合物件中新增元素 team2.add(f4); team2.add(f5); team2.add(f6); //將第二個子集合新增至大集合中 Team.add(team2); //建立第三個子集合物件ArrayList<Football> ArrayList<Football> team3 = new ArrayList<>(); Football f7 = new Football("穆里尼奧",24); Football f8 = new Football("斯帕萊蒂",27); Football f9 = new Football("弗朗西斯科利",26); //新增元素 team3.add(f7); team3.add(f8); team3.add(f9); //將第三個子集合新增至大集合中 Team.add(team3); //遍歷大集合,增強for迴圈:ArrrayList<ArrayList<Football>> for(ArrayList<Football> arrayTeam:Team){ //子集合:ArrayList<Football> for(Football arrayFootball:arrayTeam){ System.out.println(arrayFootball); } } } } class Football{ String name; int age; public Football(){ } public Football(String name, int age) { super(); 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; } //重寫toString()方法 public String toString(){ return name+","+age; } @Override //重寫equals()方法 public boolean equals(Object obj) { Football f = (Football)obj; if(f.name==this.name && f.age==this.age){ return true; } else{ return false; } } }