Nathan Sprague
OpenDSA
// List class ADT. Generalize the element type using Java Generics.
public interface List<E> { // List class ADT
// Remove all contents from the list, so it is once again empty
public void clear();
// Insert "it" at the current location
// The client must ensure that the list's capacity is not exceeded
public boolean insert(E it);
// Append "it" at the end of the list
// The client must ensure that the list's capacity is not exceeded
public boolean append(E it);
// Remove and return the current element
public E remove() throws NoSuchElementException;
// Set the current position to the start of the list
public void moveToStart();
// Set the current position to the end of the list
public void moveToEnd();
// Move the current position one step left, no change if already at beginning
public void prev();
// Move the current position one step right, no change if already at end
public void next();
// Return the number of elements in the list
public int length();
// Return the position of the current element
public int currPos();
// Set the current position to "pos"
public boolean moveToPos(int pos);
// Return true if current position is at end of the list
public boolean isAtEnd();
// Return the current element
public E getValue() throws NoSuchElementException;
// Tell if the list is empty or not
public boolean isEmpty();
}
Java Collections Framework
What will be printed by each of the following code snippets?
OpenDSA AList
java.util.ArrayList
append/add
Analysisadd
Analysisadd
AnalysisWhat is the worst-case big-\(\Theta\) running time of this method?
\(\Theta(n)\)?
\(\Theta(n^2)\)?
Somewhere in-between?
Select array assignments as the basic operation.
We want an amortized analysis… Average cost of the operation over a sequence of operations.
This table shows the total and average cost after \(n\) appends:
\(n\) | assignment cost | resize cost | total | average |
---|---|---|---|---|
1 | 1 | 0 | 1 | 1 |
2 | 1 | 1 | 3 | 1.5 |
3 | 1 | 2 | 6 | 2 |
4 | 1 | 0 | 7 | 1.75 |
5 | 1 | 4 | 12 | 2.4 |
6 | 1 | 0 | 13 | 2.167 |
7 | 1 | 0 | 14 | 2 |
8 | 1 | 0 | 15 | 1.875 |
9 | 1 | 8 | 24 | 2.667 |
… | … | … | … | … |
Total assignments equal to: \[ n + \sum_{i=0}^{\lceil \log_2 n \rceil-1} 2^{i} \]
\[ \begin{aligned} n + \sum_{i=0}^{\lceil \log_2 n \rceil-1} 2^{i} &=n + 2^{\lceil \log_2 n \rceil-1+1} - 1\\ &=n + 2^{\lceil \log_2 n \rceil} - 1 \\ &\leq n + 2^{ \log_2 n +1} - 1 \\ & = n + 2n - 1\\ &= 3n - 1 \leq 3n \end{aligned} \]
You are performing a code review on the following Java method. This is part of the software that manages an automobile’s safety features. loggingList
is an ArrayList
that stores log messages that will eventually be saved to persistent storage. Which of the following is the most appropriate evaluation of this code?
public static void respondToCollision(Area area) {
loggingList.add("Airbag Depolyed!");
if (area == Area.FRONT)
deployAirbag();
}
area == Area.FRONT
should be area.equals(Area.FRONT)
if
.