标签:
集合的嵌套遍历
需求:
自然界有很多动物的种类,猫科,犬科,鸟类这些。
那就是有很多的ArrayList<Animal>
而现在,我想要把这些ArrayList<Animal>也用集合存储,怎么办呢?
那就使用集合的嵌套使用:
就是这个样子的:ArrayList< ArrayList<Animal> >
动物类:
1 package cn_JDK5new; 2 3 public class Animal { 4 5 private String name; 6 private String color; 7 private int age; 8 9 10 11 public Animal() { 12 super(); 13 // TODO Auto-generated constructor stub 14 } 15 16 17 18 public Animal(String name, String color, int age) { 19 super(); 20 this.name = name; 21 this.color = color; 22 this.age = age; 23 } 24 25 26 public String getName() { 27 return name; 28 } 29 public void setName(String name) { 30 this.name = name; 31 } 32 public String getColor() { 33 return color; 34 } 35 public void setColor(String color) { 36 this.color = color; 37 } 38 public int getAge() { 39 return age; 40 } 41 public void setAge(int age) { 42 this.age = age; 43 } 44 45 46 }
测试类:
1 package cn_JDK5new; 2 3 import java.util.ArrayList; 4 5 import zl_ObjectTest1.Animal; 6 7 public class BigAnimalTest { 8 9 public static void main(String[] args) { 10 //创建集合1 11 ArrayList<Animal> list1 = new ArrayList<Animal>(); 12 13 //猫科 14 Animal a1 = new Animal("短尾猫","白色",1); 15 Animal a2 = new Animal("加菲猫","黄色",3); 16 Animal a3 = new Animal("波斯猫","黑色",2); 17 18 //添加进到集合1 19 list1.add(a1); 20 list1.add(a2); 21 list1.add(a3); 22 23 //创建集合2 24 ArrayList<Animal> list2 = new ArrayList<Animal>(); 25 26 //犬科 27 Animal a4 = new Animal("哈士奇","白色",1); 28 Animal a5 = new Animal("萨摩耶","纯白",2); 29 Animal a6 = new Animal("中华田园犬","黑色",2); 30 Animal a7 = new Animal("腊肠犬","黄色",3); 31 Animal a8 = new Animal("泰迪","纯白",2); 32 33 //添加进集合2 34 list2.add(a4); 35 list2.add(a5); 36 list2.add(a6); 37 list2.add(a7); 38 list2.add(a8); 39 40 41 //创建集合3 42 ArrayList<Animal> list3 = new ArrayList<Animal>(); 43 44 //鸟类 45 Animal a9 = new Animal("鸽子","白色",1); 46 Animal a10 = new Animal("老鹰","黑色",2); 47 48 //添加进集合3 49 list3.add(a9); 50 list3.add(a10); 51 52 53 //创建总的集合 54 ArrayList<ArrayList<Animal>> bigAnimal = new ArrayList<ArrayList<Animal>>(); 55 //把这些集合都放进总集合中 56 bigAnimal.add(list1); 57 bigAnimal.add(list2); 58 bigAnimal.add(list3); 59 60 //进行总集合的遍历 61 for(ArrayList<Animal> aa : bigAnimal){ 62 63 for(Animal a : aa){ 64 65 System.out.println(a.getName()+"\t"+a.getColor()+"\t"+a.getAge()); 66 } 67 } 68 } 69 }
标签:
原文地址:http://www.cnblogs.com/LZL-student/p/5898578.html