集合中存储自定义对象:
package attention;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Main_7 {
public static void main(String[] args)
{
Collection coll=new ArrayList();
coll.add(new Person("List1",21));
coll.add(new Person("List2",22));
coll.add(new Person("List3",23));
// 取出元素
Iterator it=coll.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
}
package attention;
public class Person {
private String name;
private int age;
// alt+shift+s 获得get、set方法
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}