Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously. For example, the following code traverses two parallel ArrayLists that hold the grades for different tests.
We encourage you to work in pairs or groups to tackle the following challenging FRQ problems and take them one step at a time. These will get easier with practice!
List<Integer> numList = new ArrayList<Integer>();
numList.add(new Integer(1));
numList.add(new Integer(2));
numList.add(new Integer(3));
numList.set(2,new Integer(4));
numList.add(1, new Integer(5));
numList.add(new Integer(6));
System.out.println(numList);
[1, 2, 3, 4, 5]
The set will replace the 3 at index 2 so this isn’t correct.
[1, 2, 4, 5, 6]
The add with an index of 1 and a value of 5 adds the 5 at index 1 not 3. Remember that the first index is 0.
[1, 2, 5, 4, 6]
The set will change the item at index 2 to 4. The add of 5 at index 1 will move everything else to the right and insert 5. The last add will be at the end of the list.
[1, 5, 2, 4, 6]
add without an index adds at the end, set will replace the item at that index, add with an index will move all current values at that index or beyond to the right.
The following code is supposed to initialize the ArrayList arr to [0,1,2,3,4] and then remove every other element to get [1,3]. However, when you remove an element the size of the array changes and elements move up an index! See if you can figure out why you get the unexpected result. Try the CodeLens button to trace through the code.