(使得Course类可复制)重写程序满单10-6(参见教材P319)中的Course类,增加一个clone方法,执行students域上的深度复制。
时间: 2024-02-26 15:59:28 浏览: 148
好的,以下是重写后的Course类:
```java
public class Course implements Cloneable {
private String courseName;
private ArrayList<String> students = new ArrayList<>();
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students.add(student);
}
public String[] getStudents() {
return students.toArray(new String[0]);
}
public String getCourseName() {
return courseName;
}
public int getNumberOfStudents() {
return students.size();
}
public void dropStudent(String student) {
students.remove(student);
}
@Override
public Course clone() {
try {
Course cloned = (Course) super.clone();
cloned.students = (ArrayList<String>) students.clone();
return cloned;
} catch (CloneNotSupportedException ex) {
return null;
}
}
}
```
在上述代码中,我们实现了`Cloneable`接口,并重写了`clone()`方法,使用`super.clone()`获取对象的浅拷贝,再对`students`域进行深度复制,最后返回克隆后的`Course`对象。
阅读全文