编写文件StudentDB.java:单列类,模拟数据库中的课程,初始化后至少封装5名学生信息;
时间: 2024-02-21 20:02:13 浏览: 83
好的,下面是一个简单的 StudentDB.java 的单例类示例,其中包含了5名学生的信息:
```java
import java.util.ArrayList;
import java.util.List;
public class StudentDB {
private static StudentDB instance = null;
private List<Student> students;
private StudentDB(){
students = new ArrayList<>();
students.add(new Student("S001", "Tom", "Male", "Computer Science"));
students.add(new Student("S002", "Jane", "Female", "Mathematics"));
students.add(new Student("S003", "Bob", "Male", "Electrical Engineering"));
students.add(new Student("S004", "Alice", "Female", "Mechanical Engineering"));
students.add(new Student("S005", "John", "Male", "Physics"));
}
public static StudentDB getInstance(){
if(instance == null){
instance = new StudentDB();
}
return instance;
}
public Student getStudent(String studentId){
for(Student student : students){
if(student.getId().equals(studentId)){
return student;
}
}
return null;
}
public List<Student> getStudents(){
return students;
}
}
```
以上代码实现了一个单例的 StudentDB 类,其中包含了5名学生的信息,包括学生编号、姓名、性别和专业。你可以通过调用 `getInstance()` 方法来获取该单例对象,并通过 `getStudent()` 和 `getStudents()` 方法来获取特定学生和所有学生列表。
阅读全文