(The Course class) Revise the Course class as follows: ■■ Revise the getSt
时间: 2024-05-04 09:21:27 浏览: 97
() method to return a copy of the student list instead of the original list.
Here is the revised code:
```
public class Course {
private String courseName;
private ArrayList<String> students;
public Course(String courseName) {
this.courseName = courseName;
students = new ArrayList<String>();
}
public void addStudent(String student) {
students.add(student);
}
public void dropStudent(String student) {
students.remove(student);
}
public ArrayList<String> getStudents() {
return new ArrayList<String>(students);
}
public int getNumberOfStudents() {
return students.size();
}
public String getCourseName() {
return courseName;
}
}
```
By returning a new ArrayList object containing the same elements as the original list, we are preventing external code from modifying the original list and affecting the state of the Course object. This is a form of defensive programming that can help prevent bugs and improve the robustness of our code.
阅读全文