lab3soln - public boolean add(T newEntry Search for index...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
1. // Inserts the specified date into the list in chronological order. // Precondition: list is already sorted in chronological order. public static void insert(ArrayList<CalendarDate> list, CalendarDate date) { // Find the first date in the list that is same date or later than the // date given in the parameter int index = 0; while (index < list.size() index++; } // Insert the date into the list at this position // (the add method will shift over the dates to make room) list.add(index, date); } 2. // Adds the specified entry to the list if it is not already in the list. // Invariant: List has no duplicates and is sorted in chronological order. // (An invariant is true before the method starts and is true after the // completes.
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: public boolean add(T newEntry) { // Search for index for insert point in array int index = 0; while (index < numData && dataArray[index].compareTo(newEntry) < 0) { index++; } if (dataArray[index].compareTo(newEntry) == 0) { return false; // duplicate entry - do not insert } // Check for full array: Why isn't this at the beginning of the method? if (numData == dataArray.length) { reallocate(); } // Shift data towards the end one position to make room for new // entry at position index. for (int i = numData-1; i >= index; i--) { dataArray[i+1] = dataArray[i]; } // Or instead of a loop use arraycopy: // System.arraycopy(dataArray, index, // dataArray, index+1, numData - index); dataArray[index] = newEntry; numData++; return true; }...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online