
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

CMSC 131 Spring 2005 Quiz 6 Solution
One possible solution to this problem is given below. Note that you are required to create a student copy (duplicate) and to add students appropriately when there are no students initially. Addition of a student when there are already some existing students requires finding the correct position for insertion and creation of a new array at the end.
public void add(Student student) { Student duplicate = new Student(student); Student[] newArray = null; if (array == null) { array = new Student[1]; array[0] = duplicate; } else { newArray = new Student[array.length + 1]; int startCopyingIndex = 0; if (student.getPriority() < array[0].getPriority()) { /* To the end of the list / newArray[newArray.length - 1] = duplicate; } else { / To the beginning of the list */ newArray[0] = duplicate; startCopyingIndex = 1; }
/* Copying the elements from the original array */ for (int i=0, k=startCopyingIndex; i<array.length; i++) { newArray[k++] = array[i]; }
array = newArray; } }