1. Practice: Store 5 student objects in a collection and traverse the student objects.
Analysis:
(1) Create student class
(2) Creating a Collection Object
(3) Create student objects
(4) Add students to the collection
(5) Turn the set into a group
(6) iterating through an array
2. code example:
Student.java as follows :
1 Packagecn.itcast_02;2 3 Public classStudent {4 //member Variables5 PrivateString name;6 Private intAge ;7 8 //Construction Method9 PublicStudent () {Ten Super(); One } A - PublicStudent (String name,intAge ) { - Super(); the This. Name =name; - This. Age =Age ; - } - + //member Methods - //getXxx ()/setxxx ( ) + PublicString GetName () { A returnname; at } - - Public voidsetName (String name) { - This. Name =name; - } - in Public intGetage () { - returnAge ; to } + - Public voidSetage (intAge ) { the This. Age =Age ; * } $}
also Studentdemo.java as follows:
1 Packagecn.itcast_02;2 3 Importjava.util.ArrayList;4 Importjava.util.Collection;5 6 /*7 * Practice: Store 5 student objects in a collection and traverse the student objects. 8 * 9 * Analysis:Ten * A: Create student class One * B: Create a Collection Object A * C: Create student Objects - * D: Add students to the collection - * E: Turn the set into a group the * F: Traversing an array - */ - Public classStudentdemo { - Public Static voidMain (string[] args) { + //To create a collection object -Collection C =NewArrayList (); + A //Create student Objects atStudent S1 =NewStudent ("Brigitte", 27); -Student s2 =NewStudent ("Wind Qing", 30); -Student s3 =NewStudent ("Linghutao", 33); -Student S4 =NewStudent ("Wu Xin", 25); -Student S5 =NewStudent ("Lynn Qu", 22); - in //add students to the collection - C.add (S1); to c.add (S2); + C.add (S3); - C.add (S4); the C.add (S5); * $ //Turn a collection into an arrayPanax Notoginsengobject[] Objs =C.toarray (); - //iterating through an array the for(intx = 0; x < objs.length; X + +) { + //System.out.println (objs[x]); A theStudent s =(Student) objs[x]; +System.out.println (S.getname () + "---" +s.getage ()); - } $ } $}
The results are as follows:
Java Basic Knowledge Hardening Collection Framework note 06:collection Collection store custom objects and traverse cases