Create Student class First
Package cn.itcast_04;
public class Student {
private String name;
private int age;
Public Student () {
Super ();
}
Public Student (String name, int.) {
Super ();
THIS.name = name;
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
}
To create the collection class again
Package cn.itcast_04;
Import java.util.ArrayList;
Import java.util.Collection;
Import Java.util.Iterator;
/*
* Requirements: Store custom objects and traverse student (Name,age)
*
Analysis
* A: Create student class
* B: Create a Collection Object
* C: Create student Objects
* D: Add student objects to the collection object
* E: Traversing the collection
*/
public class CollectionTest2 {
public static void Main (string[] args) {
To create a collection object
Collection C = new ArrayList ();
Create Student objects
Student S1 = new Student ("Marten Cicada", 25);
Student s2 = new Student ("Little Joe", 16);
Student s3 = new Student ("huangyueying", 20);
Student S4 = new Student ();
S4.setname ("Big Joe");
S4.setage (26);
Add a Student object to the collection object
C.add (S1);
C.add (S2);
C.add (S3);
C.add (S4);
C.add (New Student ("Sun Shangxiang",)); Anonymous Objects
Iterating through the collection
Iterator it = C.iterator ();
while (It.hasnext ()) {
Student s = (Student) it.next ();
System.out.println (S.getname () + "---" + s.getage ());
}
}
}
Or a comparative basis, I hope to help you!
This article from "GD" blog, reproduced please contact the author!
Collection Framework (collection store student objects and traverse)