用arraylist创建一个学生类
时间: 2024-03-20 07:44:45 浏览: 20
好的,以下是使用ArrayList创建一个学生类的Java代码:
```
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private int id;
public Student(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("Tom", 20, 1));
students.add(new Student("Jerry", 22, 2));
students.add(new Student("Alice", 21, 3));
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge() + ", ID: " + student.getId());
}
}
}
```
在这个例子中,我们创建了一个Student类,并使用ArrayList存储了三个学生对象。我们可以通过getName()、getAge()和getId()方法来获取学生的属性。最后,我们遍历了ArrayList并打印了每个学生的信息。