ArrayList 存储自定义对象并遍历,arraylist自定义
分享于 点击 8336 次 点评:9
ArrayList 存储自定义对象并遍历,arraylist自定义
package exercise;先创建Student类
package exercise;
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
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 age) {
this.age = age;
}
}
import java.util.ArrayList;
import java.util.Iterator;
/*ArrayList 存储自定义对象并遍历*/
public class ArrayListDemo {
public static void main(String[] args) {
// 创建集合对象
ArrayList array = new ArrayList<>();
// 创建学生对象
Student s1 = new Student("郭新兴", 25);
Student s2 = new Student("郭德纲", 55);
Student s3 = new Student("郭靖", 100);
// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
// 遍历
Iterator it = array.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName() + "----" + s.getAge());
}
System.out.println("--------");
for (int x = 0; x < array.size(); x++) {
Student s = (Student) array.get(x);
System.out.println(s.getName() + "----" + s.getAge());
}
}
}运行:
相关文章
- 暂无相关文章
用户点评