Nested traversal of a collection
Demand:
There are many kinds of animals in nature, such as cats, dogs and birds.
That's a lot of arraylist<animal>.
And now, I want to put these arraylist<animal> in the collection, how to do it?
Then use nested sets of collections:
That's what it looks like.:arraylist< arraylist<animal> >
Animal type:
1 Packagecn_jdk5new;2 3 Public classAnimal {4 5 PrivateString name;6 PrivateString color;7 Private intAge ;8 9 Ten One PublicAnimal () { A Super(); - //TODO auto-generated Constructor stub - } the - - - PublicAnimal (string name, string color,intAge ) { + Super(); - This. Name =name; + This. color =color; A This. Age =Age ; at } - - - PublicString GetName () { - returnname; - } in Public voidsetName (String name) { - This. Name =name; to } + PublicString GetColor () { - returncolor; the } * Public voidsetcolor (String color) { $ This. color =color;Panax Notoginseng } - Public intGetage () { the returnAge ; + } A Public voidSetage (intAge ) { the This. Age =Age ; + } - $ $}
Test class:
1 Packagecn_jdk5new;2 3 Importjava.util.ArrayList;4 5 ImportZl_objecttest1.animal;6 7 Public classBiganimaltest {8 9 Public Static voidMain (string[] args) {Ten //Create a Collection 1 OneArraylist<animal> List1 =NewArraylist<animal>(); A - //Cat Department -Animal A1 =NewAnimal ("Short Tail cat", "white", 1); theAnimal A2 =NewAnimal ("Garfield", "Yellow", 3); -Animal A3 =NewAnimal ("Persian cat", "Black", 2); - - //adding into the collection 1 + List1.add (A1); - List1.add (A2); + List1.add (A3); A at //Create a Collection 2 -Arraylist<animal> List2 =NewArraylist<animal>(); - - //Canine Department -Animal A4 =NewAnimal ("Husky", "white", 1); -Animal A5 =NewAnimal ("Samoyed", "pure white", 2); inAnimal A6 =NewAnimal ("Chinese Pastoral Dog", "Black", 2); -Animal A7 =NewAnimal ("Sausage dog", "Yellow", 3); toAnimal A8 =NewAnimal ("Teddy", "pure white", 2); + - //adding into the collection 2 the List2.add (A4); * List2.add (A5); $ List2.add (A6);Panax Notoginseng List2.add (A7); - List2.add (A8); the + A //Create a Collection 3 theArraylist<animal> List3 =NewArraylist<animal>(); + - //Birds $Animal A9 =NewAnimal ("Pigeon", "white", 1); $Animal A10 =NewAnimal ("Eagle", "Black", 2); - - //adding into the collection 3 the List3.add (A9); - List3.add (A10);Wuyi the - //Create a total collection WuArraylist<arraylist<animal>> Biganimal =NewArraylist<arraylist<animal>>(); - //Put these sets in the total collection About Biganimal.add (list1); $ Biganimal.add (list2); - Biganimal.add (LIST3); - - //traversal of the total collection A for(arraylist<animal>aa:biganimal) { + the for(Animal a:aa) { - $System.out.println (A.getname () + "\ T" +a.getcolor () + "\ T" +a.getage ()); the } the } the } the}
Java 16-15 Collection nesting stores and traversing elements