When declaring an ArrayList, the datatype stored in the container is specified inside of <>, and the data type must be the name of a class (no primitive data types)
The parameter to the method get represents the index in the ArrayList. The size of the ArrayList is the number of elements contained. If the ArrayList is initially empty, the size is 0.
Passing as argument - a copy of the reference to the instantiated ArrayList is passed to the method. This means that any changes made to the elements inside the method persist outside the method. The one exception to this is if you assign the argument to reference a different ArrayList in memory.
Q1: The following code is intended to store the sum of all the values in the integer ArrayList list in the variable total. Which of the following code segments can be used to replace /* missing code */ so that the code works as intended?
I. for (int pos : list)
total += pos;
II. for (int pos = 0; pos < list.size(); pos++)
total += pos;
III. for (int pos = list.size() - 1; pos >= 0; pos--)
total += list.get(pos);
int index = 0;
int count = 0;
int m = -1;
for (int outer = 0; outer < nums.size(); outer++) {
count = 0;
for (int inner = outer + 1; inner < nums.size(); inner++) {
if (nums.get(outer).equals(nums.get(inner)))
count++;
}
if (count > m) {
index = outer;
m = count;
}
} // end outer for
System.out.println(index);
Prints the maximum value that occurs in the ArrayList nums
Q3: The following code is intended to store the largest value in the integer ArrayList list in the variable maxVal. Which of the following best describes the conditions under which the code will not work as intended?
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int target = /* some value */ ;
ArrayList<Integer> delta = new ArrayList<>();
for (int i = 1; i < 10; i++)
delta.add(i * 10);
boolean found = false;
int x = 0;
for (x = 0; x < delta.size() && !found; x++) {
if (delta.get(x) == target)
found = true;
}
manipulate(delta, found, x);
}
public static void manipulate(ArrayList<Integer> aList, boolean f, int spot) {
if (f)
aList.remove(spot - 1);
aList.add(-999);
}
} // end class
Removes the value preceding a specific value in the list and adds -999 to the end of the list