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

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

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



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值