2026 03 18 ArrayList Review

Three practice ArrayList problems. Do after presentation problems.

The notation [“A”, “B”] on this page means the ArrayList<String> containing “A” and “B”. That is not actually legal Java.

  1. Add up all of the odd nunmbers in the list.

     public static int oddSum (ArrayList<Integer> nums)
    
  2. Insert the word y after every word "doc" in the original xs. Modify xs.

     public static void cs (String y, ArrayList<String> xs)
    
     xs1 = ["orange","doc","grape","doc"])
     cs("apple", xs1);
     xs1.equals(["orange", "doc", "apple", "grape", "doc", "orange"]);
    
     xs2 = ["doc", "mo"]
     cs("doc",xs2);
     xs2.equals(["doc", "doc", "mo"])
    

3. Complex ArrayList Problem

The function tf has the signature:

    public static double tf (double tot, ArrayList<Double> ws)

This function mutates the ws list as well as returning an answer.

  1. Keep a running total of each number in the list. Begin the running total at the number tot.
  2. After adding each number, check to see if the running total is greater than 10.0. If it is:
    1. Insert that value into the ArrayList ws immediately after the value just added.
    2. Subtract 10 from the total.
    3. Continue with the next number in the original list.
  3. Return the final “total” (taking subtractions into account).

Example:

    tf (6.50, [3.00, 2.75, 4.50])
  • The first term is 3.00. The running total becomes $6.50+3.00 = 9.50$.

  • The second term is 2.75. The running total becomes $9.50 + 2.75 = 12.25$. This is over 10.0, so mutate the ws array so that it becomes:

          [3.00, 2.75, 12.25, 4.50]
    

    Also, subtract 10 so that the running total is now $12.25 - 10.00 = 2.25$.

  • The “third” (now really fourth) term is 4.50. The running total is now $2.25 + 4.50 = 6.75$.

  • The result from running this function is 6.75.