1. Collection Collection stores student objects and iterates through:
Requirements: Store custom objects and traverse student (Name,age)
Analysis:
(1) Create student class
(2) Creating a Collection Object
(3) Create student objects
(4) Adding student objects to the collection object
(5) Traversing the collection
2. code example:
Student.java, as follows:
1 Packagecn.itcast_04;2 3 Public classStudent {4 PrivateString name;5 Private intAge ;6 7 PublicStudent () {8 Super();9 }Ten One PublicStudent (String name,intAge ) { A Super(); - This. Name =name; - This. Age =Age ; the } - - PublicString GetName () { - returnname; + } - + Public voidsetName (String name) { A This. Name =name; at } - - Public intGetage () { - returnAge ; - } - in Public voidSetage (intAge ) { - This. Age =Age ; to } + -}
Write a test class CollectionTest2 again, as follows:
1 Packagecn.itcast_04;2 3 Importjava.util.ArrayList;4 Importjava.util.Collection;5 ImportJava.util.Iterator;6 7 /*8 * Requirements: Store custom objects and traverse student (Name,age)9 *Ten * Analysis: One * A: Create student class A * B: Create a Collection Object - * C: Create student Objects - * D: Add student objects to the collection object the * E: Traversing the collection - */ - Public classCollectionTest2 { - Public Static voidMain (string[] args) { + //To create a collection object -Collection C =NewArrayList (); + A //Create student Objects atStudent S1 =NewStudent ("Marten Cicada", 25); -Student s2 =NewStudent ("Little Joe", 16); -Student s3 =NewStudent ("huangyueying", 20); -Student S4 =NewStudent (); -S4.setname ("Big Joe"); -S4.setage (26); in - //add a Student object to the collection object to C.add (S1); + c.add (S2); - C.add (S3); the C.add (S4); *C.add (NewStudent ("Sun Shangxiang", 18));//Anonymous Objects $ Panax Notoginseng //iterating through the collection -Iterator it =c.iterator (); the while(It.hasnext ()) { +Student s =(Student) It.next (); ASystem.out.println (S.getname () + "---" +s.getage ()); the } + } -}
The results are as follows:
Java basic Knowledge Hardening Collection Framework note 13:collection Collection store student objects and traverse