Packagecn.itcast_04; Public class Student { PrivateString name;Private intAge Public Student() {Super(); } Public Student(String name,intAge) {Super(); This. name = name; This. Age = Age; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }}
Packagecn.itcast_04;ImportJava.util.ArrayList;ImportJava.util.Collection;ImportJava.util.Iterator;/* Requirements: Store strings and traverse. * * Analysis: * A: Create a Collection Object * B: Create a String Object * C: Add a String object to the collection * D: Traverse the collection * * Public class collectiontest { Public Static void Main(string[] args) {//Create collection ObjectCollection C =NewArrayList ();//Create a String object //Add a String object to the collectionC.add ("Brigitte"); C.add ("The Wind"); C.add ("Elina"); C.add ("Wu Xin"); C.add ("Lynn Song");//Traversal collection //Get an iterator object from a collection objectIterator it = C.iterator ();//Use the Hasnext () method of the Iterator object to determine if there are any elements while(It.hasnext ()) {//Get the element by the next () method of the Iterator objectstring s = (string) it.next (); System.out.println (s); } }}
Packagecn.itcast_04;ImportJava.util.ArrayList;ImportJava.util.Collection;ImportJava.util.Iterator;/ * Requirements: Store custom objects and traverse student (name,age) * Analysis: * A: Create student class * B: Create Collection Object * C: Create student Object * D: Add student object to collection Object * E: Traversal Collection */ Public class CollectionTest2 { Public Static void Main(string[] args) {//Create collection ObjectCollection C =NewArrayList ();//Create student ObjectsStudent S1 =NewStudent ("Mink Cicada", -); Student s2 =NewStudent ("Little Joe.", -); Student s3 =NewStudent ("Huangyueying", -); Student S4 =NewStudent (); S4.setname ("Big Joe"); S4.setage ( -);//Add a Student object to the collection objectC.add (S1); C.add (S2); C.add (S3); C.add (S4); C.add (NewStudent ("Sun Shangxiang", -));//Anonymous object //Traversal collectionIterator it = C.iterator (); while(It.hasnext ()) {Student s = (Student) it.next (); System.out.println (S.getname () +"---"+ s.getage ()); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Collection Collection Detailed 4