用List集合存储学生对象并遍历
Student.java
package com.hui.list;
public class Student {
private String name;
private String age;
public Student() {
super();
}
public Student(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return getName()+"..."+getAge();
}
}
Test1.java
package com.hui.Test;//List集合存储学生对象并遍历
import java.util.ArrayList;
import java.util.List;
import com.hui.list.Student;
public class Test1 {
public static void main(String[] args) {
List<Student> list1 = new ArrayList();
//初始化
list1.add(new Student("张三","23")); //这里相当于 Object obj = new Student("张三","23")向上转型成了父类
list1.add(new Student("李四", "24"));
list1.add(new Student("王五","25"));
for(int i = 0;i<list1.size();i++) {
System.out.println(list1.get(i)); //通过索引获取每个元素
/*Student st = (Student)list1.get(i);
System.out.println(st.getName()+"..."+st.getAge());*/
//若是想通过getName(),getAge()来显示,必须让list1变为Student类型才能调用其下方法
}
}
}
运行结果: