Nathan Sprague
9/9/2020
What will be printed when this code executes?
List<Integer> numbers = new AList<>();
for (int i = 0; i < 10000; i++) {
numbers.append(i);
}
System.out.println(numbers.length());
What will be printed when this code executes?
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
numbers.add(i);
}
System.out.println(numbers.size());
add
Analysisadd
Analysisadd
AnalysisWhat is the worst-case big-\(\Theta\) running time of this method?
public static void addNumbers(int n) {
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < n; i++) {
nums.add(i); // Best case Theta(1), worst case Theta(n)
}
}
Somewhere in-between?
This table shows the total 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
.