import java.util.*;
class ArrayListText
{
public static void main(String[] args)
{
mother();
}
public static void mother(){
//建立集合
ArrayList al = new ArrayList();
//建立Person对象
Person p1 = new Person("乔震宇",20);
Person p2 = new Person("曹丹",21);
Person p3 = new Person("黄献民",26);
Person p4 = new Person("景迪",100);
//调用集合的add方法,将自定义的Person对象存储到集合
al.add(p1);
al.add(p2);
al.add(p3);
al.add(p4);
//用迭代器获取集合中的元素
Iterator it = al.iterator();
while(it.hasNext())
Person p=(Person)it.next();
System.out.println(p.getName()+" "+p.getAge());
}
}
Person类也创建好了但是运行提示错误信息
C:\Users\Administrator\Desktop
---------- 编译javac ----------
ArrayListText.java:24: 错误: 不是语句
Person p=(Person)it.next();
^
ArrayListText.java:24: 错误: 需要';'
Person p=(Person)it.next();
^
2 个错误
public static void main(String[] args) {
new Test1().mother();
}
public static void mother(){
//建立集合
ArrayList al = new ArrayList();
//建立Person对象
Person p1 = new Person("乔震宇",20);
Person p2 = new Person("曹丹",21);
Person p3 = new Person("黄献民",26);
Person p4 = new Person("景迪",100);
//调用集合的add方法,将自定义的Person对象存储到集合
al.add(p1);
al.add(p2);
al.add(p3);
al.add(p4);
//用迭代器获取集合中的元素
Iterator it = al.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
System.out.println(p.getName()+" "+p.getAge());
}
}
}
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
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 age) {
this.age = age;
}