Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question: Modify the Course class to add a clone method to perform a deep copy o

ID: 3814806 • Letter: Q

Question

Question:

Modify the Course class to add a clone method to perform a deep copy on the students field. You can use a utility method for performing this deep copy.

public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;

public Course(String courseName) {
this.courseName = courseName;
}

public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}

public String[] getStudents() {
return students;
}

public int getNumberOfStudents() {
return numberOfStudents;
}

public String getCourseName() {
return courseName;
}

/*******clone method goes here**********/


}

Explanation / Answer

When we want to copy arrays or objects, we can do a deep copy or a shallow copy.

Shallow Copy :- In case of shallow copy , when we copy the array we just copy the reference.This may cause side effects if the elements of values are changed via some other reference.

public Course(String course_Name,string[] str,int NumStudents) {
this.courseName = course_Name;
   this.students = str;
   this.numberOfStudents=NumStudents;
}

Deep copy :- In case of deep copy, we actually allocate the memory to array and assign elements value one by one.

public Course(const Course &cobj)
{
   this.courseName = cobj.courseName;
   this.numberOfStudents = cobj.numberOfStudents;
   this.students = new String[100];
   for (int i = 0; i < 100; i++) {
this.students[i] = cobj.students[i];
}
}
  
So Ans:
public Course(const Course &cobj)
{
   this.courseName = cobj.courseName;
   this.numberOfStudents = cobj.numberOfStudents;
   this.students = new String[100];
   for (int i = 0; i < 100; i++) {
this.students[i] = cobj.students[i];
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote