03 深入了解Java集合之增强for循环

一 增强for循环(掌握)
(1)是for循环的一种
(2)格式:
for(元素的数据类型 变量名 : 数组或者Collection集合的对象) {
使用该变量即可,该变量其实就是数组或者集合中的元素。
}
(3)好处:
简化了数组和集合的遍历
(4)弊端

增强for循环的目标不能为null。建议在使用前,先判断是否为null。

二 练习题

集合的嵌套遍历

package it.Collection;

import java.util.ArrayList;

public class listTest01 {
	// 集合的嵌套遍历
	/*
	 * 假设我们班有5个学生,组成一个集合,ArrayList<Student>; 隔壁班有3个学生,组成一个集合,ArrayList<Student>;
	 * 斜对班有2个学生,组成一个集合,ArrayList<Student>;
	 * 现在我想把三个班的学生都放到一个集合里,进行遍历ArrayList<ArrayList<Student>>
	 * 
	 * A 必须要有个学生类 B 将每个学生集合放入大集合中 C 遍历大集合出每个学生
	 */
	public static void main(String[] args) {
		// 第一:定义大集合
		ArrayList<ArrayList<Student>> BigArray = new ArrayList<ArrayList<Student>>();
		// 第一:定义第一集合 并添加元素 放入大集合中
		Student s1 = new Student("唐僧", 20);
		Student s2 = new Student("孙悟空", 21);
		Student s3 = new Student("猪八戒", 22);
		Student s4 = new Student("沙和尚", 23);
		ArrayList<Student> one = new ArrayList<Student>();
		one.add(s1);
		one.add(s2);
		one.add(s3);
		one.add(s4);
		BigArray.add(one);
		// 第二:定义第二个集合 并添加元素 放入大集合中
		Student s5 = new Student("曹操", 30);
		Student s6 = new Student("刘备", 25);
		Student s7 = new Student("孙权", 1);
		ArrayList<Student> two = new ArrayList<Student>();
		two.add(s5);
		two.add(s6);
		two.add(s7);
		BigArray.add(two);
		// 第三:定义第三个集合 并添加元素 放入大集合中
		Student s8 = new Student("司马懿", 22);
		Student s9 = new Student("诸葛亮", 21);
		ArrayList<Student> third = new ArrayList<Student>();
		third.add(s8);
		third.add(s9);
		BigArray.add(third);
		for (ArrayList<Student> x : BigArray) {
			for (Student y: x) {
				System.out.println(y.getName() + "--------" + y.getAge());
			}
		}
	}
}

获取101-20之间的随机数,要求不能重复

package it.Collection;

import java.util.ArrayList;
import java.util.Random;



public class listTest02 {
	// 获取10个1-20之间的随机数,要求不能重复:Math.random()--获取随机数方法 
	/* 用数组实现,但是数组的长度是固定的,长度不好确定
	 * 所以我们用集合来实现
	 * A 创建产生随机数的对象
	 * B 创建一个存储随机数的集合
	 * C 定义一个统计变量,从0开始
	 * D 判断统计变量是否小于10
	 * 是:先产生一个随机数,判断随机数在集合中是否存在 ,
	 *      不存在则添加,统计变量++,
	 *      存在,不搭理
	 * 否: 就退出循环
	 * E 遍历集合即可
	 */
	public static void main(String[] args) {
		// 创建产生随机数的对象
		Random r= new Random();
		// 创建一个存储随机数的集合
		ArrayList<Integer> Array = new ArrayList<Integer>();
//		定义一个统计变量,从0开始
		int count =0;
		//判断统计变量是否小于10
		while(count <10){
			//先产生一个随机数
			int number  = r.nextInt(20)+1;
			//判断随机数在集合中是否存在 
			if(!Array.contains(number)){
			//	不存在则添加,统计变量++
				Array.add(number);
				count++;
			}
		}
		for(Integer i:Array){
			System.out.println(i);
			
		}
	}
}

猜你喜欢

转载自blog.csdn.net/zhangxinxin1108/article/details/79298133