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

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

ArrayList表示一个班级,而年级大的集合则可用:ArrayList>来表示


图解:

【我的Java笔记】ArrayList集合的遍历嵌套_第1张图片


/*
 * 集合的遍历嵌套
 * 大集合:ArrayList>
 * */

import java.util.ArrayList;

public class FootballTest {
	public static void main(String[] args){
		//创建ArrayList大集合对象
		ArrayList> Team = new ArrayList<>();
		
		//创建第一个子集合对象ArrayList
		ArrayList 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
		ArrayList 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
		ArrayList 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>
		for(ArrayList arrayTeam:Team){
			//子集合:ArrayList
			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;
		}
	}
	
}


【我的Java笔记】ArrayList集合的遍历嵌套_第2张图片

你可能感兴趣的:(JavaSE)