【我的Java笔记】ArrayList集合的遍历嵌套

来源:互联网 发布:淘宝空单号多少钱一个 编辑:程序博客网 时间:2024/06/06 08:51

例子:假设有一个年级,一个年级中存在多个班级,而班级中的每一个学生都是一个对象

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;}}}



原创粉丝点击