解题思路:
题目首先要求要有四个学生对象,那我们首先得先建立学生类呀,为了方便起见,学生类的对象我就只有名字和年龄好了。
除了成员变量是我自己写的,其他都是电脑点点鼠标就好了,之前的博文有介绍了,可以去看看~
package cn.itcast.day0605.demo03;
public class Demo05Student {
private String name;
private int 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;
}
public Demo05Student() {
}
public Demo05Student(String name, int age) {
this.name = name;
this.age = age;
}
}
接下来,要放在集合里面的,因此也要建立集合类:
ArrayList list = new ArrayList<>();
//注意:尖括号里面其实是Student类类型。由你上面命名来写。
第三步,要new四个Demo05Student对象
Demo05Student one = new Demo05Student("吴亦凡",20);
Demo05Student two = new Demo05Student("粉丝1",10);
Demo05Student three = new Demo05Student("粉丝2",15);
Demo05Student four = new Demo05Student("晓婷",18);
第四步,将这四个对象放进集合里面:
list.add(one);
list.add(two);
list.add(three);
list.add(four);
遍历,直接list.fori+回车:
for (int i = 0; i < list.size(); i++) {
System.out.println("姓名:"+list.get(i).getName()+",年龄为:"+list.get(i).getAge());
}
完整代码:
package cn.itcast.day0605.demo03;
import java.util.ArrayList;
/*
自定义四个学生对象,添加到集合并遍历集合
*/
public class Demo05ArrayListExercise2 {
public static void main(String[] args) {
ArrayList<Demo05Student> list = new ArrayList<>();
Demo05Student one = new Demo05Student("吴亦凡",20);
Demo05Student two = new Demo05Student("粉丝1",10);
Demo05Student three = new Demo05Student("粉丝2",15);
Demo05Student four = new Demo05Student("晓婷",18);
list.add(one);
list.add(two);
list.add(three);
list.add(four);
for (int i = 0; i < list.size(); i++) {
System.out.println("姓名:"+list.get(i).getName()+",年龄为:"+list.get(i).getAge());
}
}
}
运行结果:
有帮助到你的话能小小点赞嘛~