定义ArrayList存储如上学生对象信息,并遍历展示出来
时间: 2023-07-19 19:08:25 浏览: 100
好的,以下是Java代码示例:
```java
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private String gender;
private String major;
public Student(String name, int age, String gender, String major) {
this.name = name;
this.age = age;
this.gender = gender;
this.major = major;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getMajor() {
return major;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("张三", 20, "男", "计算机科学"));
students.add(new Student("李四", 21, "女", "信息工程"));
students.add(new Student("王五", 22, "男", "通信工程"));
for (Student student : students) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge()
+ ",性别:" + student.getGender() + ",专业:" + student.getMajor());
}
}
}
```
运行结果:
```
姓名:张三,年龄:20,性别:男,专业:计算机科学
姓名:李四,年龄:21,性别:女,专业:信息工程
姓名:王五,年龄:22,性别:男,专业:通信工程
```
阅读全文