IDEA选择集合作为Student类的容器
时间: 2023-08-13 17:09:14 浏览: 51
好的,我明白了。如果您想在Java中实现一个Student类,并使用集合作为其容器,可以使用Java集合框架中的List、Set或Map等来实现。以下是一个示例代码:
```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
List<Student> studentsList = new ArrayList<>(); // 使用List作为容器
Set<Student> studentsSet = new HashSet<>(); // 使用Set作为容器
studentsList.add(new Student("Alice", 20));
studentsList.add(new Student("Bob", 19));
studentsList.add(new Student("Charlie", 21));
studentsSet.add(new Student("Alice", 20));
studentsSet.add(new Student("Bob", 19));
studentsSet.add(new Student("Charlie", 21));
for (Student s : studentsList) {
System.out.println(s.getName() + " (" + s.getAge() + ")");
}
for (Student s : studentsSet) {
System.out.println(s.getName() + " (" + s.getAge() + ")");
}
}
}
```
在这个示例中,定义了一个Student类,它有一个姓名和年龄的成员变量,并使用构造函数来初始化它们。然后,使用List和Set来存储Student对象,并使用add方法来插入新的Student对象。最后,使用增强for循环遍历List和Set中的Student对象,并输出它们的姓名和年龄。