package edu.tjcu.wfh1.Demo05;
import java.util.ArrayList;
/*题目:
自定义4个学生对象,添加到集合,并遍历。
思路:
1.自定义Student学生类,四个部分。
1.所有的成员变量都要用private
2.无参构造
3.全参构造
4.Getter,Setter
2.创建—个集合,用来存储学生对象。泛型:<Student>
3.根据类,创建4个学生对象。
4将4个学生对象添加到集合中: add
5.遍历集合:for、 size、get
*/
public class Demo02ArrayListStudent {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student one = new Student("逆天而行",18);
Student two = new Student("随风起舞",19);
Student three = new Student("星星有泪",20);
Student four = new Student("不闻不问",21);
Student five = new Student("苍白的脸",22);
list.add(one);
list.add(two);
list.add(three);
list.add(four);
list.add(five);
for (int i = 0; i < list.size(); i++) {
System.out.println("姓名:" + list.get(i).getName() + " " + "年龄:" + list.get(i).getAge());
}
}
}
package edu.tjcu.wfh1.Demo05;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(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;
}
}
20 . 遍历类
最新推荐文章于 2023-05-24 19:57:36 发布