Requirement: ArrayList stores custom objects and iterates through them. Requires generics to be joined and enhanced for traversal.
A: iterators
B: General for
C: Enhanced for
Linkedlist,vector,colleciton,list and other storage continue to practice
The enhanced for is used to replace iterators.
1 Packagecn_jdk5new;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6 7 Public classArrListDemo2 {8 Public Static voidMain (string[] args) {9 //Create a collection note: Here is a custom object to be stored, then the class name of the object to fill in the typeTenarraylist<person> alt =NewArraylist<person>(); One A //To create a custom object -person S1 =NewPerson ("Ah-cat", "female", 20); -Person S2 =NewPerson ("Ah dog", "male", 22); thePerson S3 =NewPerson ("Zhang San", "male", 19); -Person S4 =NewPerson ("Alar", "female", 20); - - //adding elements to a collection + Alt.add (S1); - alt.add (S2); + Alt.add (S3); A Alt.add (S4); at - //Traverse - //iterators -Iterator<person> it =alt.iterator (); - while(It.hasnext ()) { -person P1 =It.next (); inSystem.out.println (P1.getname () + "\ T" +p1.getsex () + "\ T" +p1.getage ()); - } toSystem.out.println ("------------"); + - //General for the for(intx = 0;x < Alt.size (); X + +){ *Person p2=alt.get (x); $System.out.println (P2.getname () + "\ T" +p2.getsex () + "\ T" +p2.getage ());Panax Notoginseng } -System.out.println ("------------"); the + //Enhanced for A for(person P3:alt) { theSystem.out.println (P3.getname () + "\ T" +p3.getsex () + "\ T" +p3.getage ()); + } - } $}
Java 16-11 ArrayList Store custom objects and enhance for traversal