Skip to main content
Logo image

Section 10.5 Summary and exercises

In this chapter you learned about ArrayLists which are dynamic re-sizable arrays. You learned how to declare and create ArrayLists, add and remove objects from them, set the object at an index, and get the object at an index.
List are like arrays in that you can store many objects of the same type in a list, just as you can in an array. Lists are different from arrays in that they can grow or shrink as needed. You can also add an element anywhere in a list and remove an element from any index. The first element in a list is at index 0 just like arrays.
Lists also differ from arrays in that you can have an array of any of the primitive types: int, double, or boolean, but you can only put objects in a list. You can use the wrapper classes Integer, Double, and Boolean to wrap a primitive value in an object so that you can put it in a list. Java will also do this automatically for you if you try to add a primitive value to a list or set a primitive variable to an item of a list. This is called autoboxing and unboxing.

Subsection 10.5.1 Concept Summary

  • Autoboxing - Automatically wrapping a primitive type in a wrapper class object. For instance if you try to add an int value to a list, it will automatically be converted to an Integer object.
  • Abstract Method - A method that only has a declaration and no method body (no code inside the method).
  • ArrayList - An ArrayList can hold many objects of the same type. It can grow or shrink as needed. You can add and remove items at any index.
  • Add - You can add an object to the end of a list using listName.add(obj). You can add an object at an index of a list using add(index,obj). This will first move any objects at that index or higher to the right one position to make room for the new object.
  • Declaration - To declare an ArrayList use ArrayList<Type> name, where Type is the class name for the type of objects in the list. If you leave off the <Type> it will default to Object.
  • Creation - To create an ArrayList use new ArrayList<Type>, where Type is the class name for the type of objects you want to store in the list. There are other classes that implement the List interface, but you only need to know the ArrayList class for the exam.
  • Get - To get an object at an index from a list use listName.get(index).
  • Index - You can access and set values in a list using an index. The first element in a list called list1 is at index 0 list1.get(0). The last element in a list is at the length minus one - list1[list1.size() - 1].
  • Remove - To remove the object at an index use ListName.remove(index). This will move all object past that index to the left one index.
  • Set - To set the value at an index in a list use listName.set(index,obj).
  • Size - Use listName.size() to get the number of objects in the list.
  • Wrapper Class - Classes used to create objects that hold primitive type values like Integer for int, Double for double and Boolean for boolean.
  • Unboxing - Automatically converting a wrapper object like an Integer into a primitive type such as an int.

Subsection 10.5.2 Vocabulary Practice

Activity 10.5.1.

Activity 10.5.2.

For more practice, see this Quizlet.

Subsection 10.5.3 Common Mistakes

  • forgetting that set replaces the item at the index
  • forgetting that remove at an index moves all items that were to the right of that index left one index
  • forgetting that add at an index moves everything that was at the index and greater to the right one index
  • incrementing an index when looping through a list even though you removed an item from the list
  • using nameList[0] instead of nameList.get(0).
  • using nameList.length instead of nameList.size() to get the number of elements in a list

Subsection 10.5.4 Practice problems

Activity 10.5.3.

You should be able to trace through code that uses all the basic ArrayList methods like the following.
What will print when the following code executes?
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);
You can step through the code above by clicking on the following Example1.
  • [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.

Activity 10.5.4.

What will print when the following code executes?
List<Integer> list1 = new ArrayList<Integer>();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.remove(1);
System.out.println(list1);
You can step through the code above by clicking on the following Example2.
  • [2, 3]
  • The remove will remove the item at the given index.
  • [1, 2, 3]
  • The item at index 1 will be removed and all the other values shifted left.
  • [1, 2]
  • The 3 is at index 2. The item at index 1 will be removed.
  • [1, 3]
  • The item at index 1 is removed and the 3 is moved left.

Activity 10.5.5.

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.

Activity 10.5.6.

The following method should calculate the average from an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution.

Activity 10.5.7.

The following program segment is a method that should return the minimum int given an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.8.

Create a findMax method that finds and returns the largest value in an ArrayList of Integers.

Activity 10.5.9.

The following program segment is a method that should return true if at least one element in an ArrayList of Integers (the parameter) is even. But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.10.

Write a method countOdd that returns the number of odd numbers in an ArrayList of Integers.

Activity 10.5.11.

The following program segment is a method that should return true if there are any duplicate elements in an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.12.

Write a method hasDuplicates that returns true if there are any duplicate elements in an ArrayList of Integers.

Activity 10.5.13.

The following program segment is a method that should rotate the elements in an ArrayList of Integers (the parameter) to the right by one position. But, the blocks have been mixed up and include extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.14.

Write a method rotateLeft that rotates the elements in an ArrayList of Integers to the left by one position.

Activity 10.5.15.

The following program segment should be a method that traverses through an ArrayList of Strings (the parameter) and print out the elements in reverse order – so {β€œcat”, β€œdog”, β€œmouse”} should print β€œmouse, dog, cat, ” as output. Assume the ArrayList β€œmyList” has been instantiated and filled with Strings. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.16.

Complete the method reverse below to return an ArrayList containing Integers in the reversed order of the ArrayList parameter list. Hint: use a for loop with one line inside it to add to the new list.

Activity 10.5.17.

Complete the code below to add the items in parallel ArrayLists to total.

Subsection 10.5.5 ArrayList Mixed Up Code Practice

Try to solve each of the following. Click the Check button to check each solution. You will be told if your solution is too short, has a block in the wrong order, or you are using the wrong block. Some of the problems have an extra block or two that aren’t needed in the correct solution. Try to solve these on your phone or other mobile device!

Activity 10.5.18.

The following program segment should be a class that adds some Strings of conversational phrases to a List and then prints them out. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution.

Activity 10.5.19.

The following program segment should be a method that traverses through an ArrayList of Strings (the parameter) and print out the elements in reverse order – so {β€œcat”, β€œdog”, β€œmouse”} should print β€œmouse, dog, cat, ” as output. Assume the ArrayList β€œmyList” has been instantiated and filled with Strings. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the needed blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.20.

The following program segment should remove all the zeros from an ArrayList of Integers. Assume the ArrayList β€œlistOfNums” has been instantiated and filled with Integers. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.21.

The following program segment is a method that should return the smallest int given an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.22.

The following program segment is a method that should remove all the positive and negative odd values in an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.23.

The following method should calculate the average from an ArrayList of Integers (the parameter). But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution.

Activity 10.5.24.

The following program segment is a method that should find the largest value given an ArrayList of Integers (the parameter) and move it to the back of the list. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.25.

The following method should remove all the Strings that have length 3 or shorter from an ArrayList of Strings (the parameter) – so {β€œcatch”, β€œdog”, β€œtree”, β€œme”} should return {β€œcatch”, β€œtree”}. But, the blocks have been mixed up and include one extra block that is not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution.

Activity 10.5.26.

The following program segment is a method that should take each String from an ArrayList of Strings (the parameter) and add it again to the list – so {β€œcat”, β€œribbon”, β€œhouse”} should become {β€œcat”, β€œcat”, β€œribbon”, β€œribbon”, β€œhouse”, β€œhouse”}. But, the blocks have been mixed up and include two extra blocks that are not needed in a correct solution. Drag the blocks from the left and put them in the correct order on the right. Click the Check button to check your solution.

Activity 10.5.27.

The following method should remove a specific Integer (specified in parameter) whenever it occurs in a given ArrayList of Integers (the parameter). But, the blocks have been mixed up and include three extra blocks that are not needed in a correct solution. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly. Click the Check button to check your solution.

Subsection 10.5.6 Code Practice with ArrayLists

Activity 10.5.28.

Fix the following code so that it compiles. The code should instantiate an ArrayList of Strings names and fill it with the Strings from the array friends. It should then print out names.
Solution.
In line 10, change the terminating condition to i < friends.length so that you don’t go out of bounds of the array.
import java.util.*;

public class Test1
{
    public static void main(String[] args)
    {
        ArrayList<String> names = new ArrayList<String>();
        String[] friends = {"Sam", "Jessica", "Mark", "Alexis"};
        for (int i = 0; i < friends.length; i++)
        {
            names.add(friends[i]);
        }
        System.out.println(names);
    }
}

Activity 10.5.29.

Fix the following class so that it will compile and the method reverse will return an ArrayList containing Integers in the reversed order of the ArrayList parameter list. Hint: for this solution, only one line needs to be added to the for-loop inside of the reverse method.
Solution.
Change line 8 int to Integer because ArrayLists only store objects and int is a primitive. Add in line 11 reversed.add(0, element); so that each element of the ArrayList list, the parameter, is added in front of the previously added element (thereby reversing the order).
Note that there are other equally correct ways to reverse the order of the ArrayList without creating a new Array or by traversing through it backwards.
import java.util.*;

public class Test1
{
    public static ArrayList<Integer> reverse(ArrayList<Integer> list)
    {
        ArrayList<Integer> reversed = new ArrayList<Integer>();
        for (Integer element : list)
        {
            reversed.add(0, element);
        }
        return reversed;
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {1, 5, 7, 9, -2, 3, 2};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        ArrayList<Integer> result = reverse(values);
        System.out.println("Expected Result:\t [2, 3, -2, 9, 7, 5, 1]");
        System.out.println("Your Result:\t\t " + result);
    }
}

Activity 10.5.30.

Fix the following method printEvenIndex so that it will print out the Integers at even indices of the passed-in ArrayList list.
Solution.
In line 8, the for loop should be written as for (int i = 0; i < list.size(); i++) so that the method will traverse through all elements of the ArrayList list. In the line 10 conditional, it should be checking when the index, i is even - in other words, checking if it is divisible by 2 with no remainder: i % 2 == 0.
import java.util.*;

public class Test1
{
    public static void printEvenIndex(ArrayList<Integer> list)
    {
        for (int i = 0; i < list.size(); i++)
        {
            if (i % 2 == 0)
            {
                System.out.print(list.get(i) + ", ");
            }
        }
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {1, 5, 7, 9, -2, 3, 2};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        System.out.println("Expected Result:\t 1, 7, -2, 2,");
        System.out.print("Your Result:\t\t ");
        printEvenIndex(values);
    }
}

Activity 10.5.31.

Fix the following method printEvenElements so that it will print out all of the even Integers that are in the passed-in ArrayList list.
Solution.
In line 7, ArrayLists do not have a length property; instead, call the size() method to find out how long an ArrayList is.
import java.util.*;

public class Test1
{
    public static void printEvenElements(ArrayList<Integer> list)
    {
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i) % 2 == 0)
            {
                System.out.print(list.get(i) + ", ");
            }
        }
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {1, 44, 7, 9, -16, 3, 2};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        System.out.println("Expected Result:\t 44, -16, 2,");
        System.out.print("Your Result:\t\t ");
        printEvenElements(values);
    }
}

Activity 10.5.32.

Rewrite the following code so that it fills the ArrayList values with the elements of the array nums using a for-each loop instead of a for loop.
Solution.
In a for-each loop you specify the type of the values in the array, a name for the current value, and then a : and then the name of the array. You then want to add each element to the values ArrayList.
import java.util.ArrayList;

public class Test1
{
    public static void main(String[] args)
    {
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {1, 44, 7, 9, -16, 3};
        for (int element : nums)
        {
            values.add(element);
        }
        System.out.println("Expected Result:\t [1, 44, 7, 9, -16, 3]");
        System.out.println("Your Result:\t\t " + values);
    }
}

Activity 10.5.33.

Finish the following method ``sumNegVal`` to return the sum of all of the negative numbers in the ArrayList ``list``, the parameter.
Solution.
Declare a variable to hold the sum and initialize it to zero. Loop through all the values in the ArrayList. If the current value is negative (less than 0) then add it to the sum. Return the sum.
import java.util.ArrayList;

public class Test1
{
    public static int sumNegValues(ArrayList<Integer> list)
    {
        int sum = 0;
        for (Integer element : list)
        {
            if (element < 0)
            {
                sum += element;
            }
        }
        return sum;
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {-2, 34, -11, 9, -6, 3};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        System.out.println("Expected Result:\t -19");
        System.out.print("Your Result:\t\t ");
        System.out.println(sumNegValues(values));
    }
}

Activity 10.5.34.

Finish the following method β€˜β€™removeLongStrings’’ that checks each element of the passed in ArrayList list and removes any that are strictly longer than 4 characters.
Solution.
Loop through all of the elements of the ArrayList list. In each iteration, check if the length of each element is strictly greater > than 4; if it is, remove that element.
import java.util.ArrayList;

public class Test1
{
    public static void removeLongStrings(ArrayList<String> list)
    {
        int count = 0;
        while (count < list.size())
        {
            if (list.get(count).length() > 4)
            {
                list.remove(count);
            }
            else
            {
                count++;
            }
        }
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<String> values = new ArrayList<String>();
        String[] words = {"bathtub", "fish", "computer", "cat", "foo"};
        for (int i = 0; i < words.length; i++)
        {
            values.add(words[i]);
        }
        removeLongStrings(values);
        System.out.println("Expected Result:\t [fish, cat, foo]");
        System.out.println("Your Result:\t\t " + values);
    }
}

Activity 10.5.35.

Fill in the method shiftLeftOne below to shift all of the elements of the passed-in ArrayList list left by one. The original first element should be wrapped to the back of the list after the shift. Ex: {1, 2, 3, 4} should turn turn into {2, 3, 4, 1}
Solution.
Remove the first element of list and save it to a new variable of type Integer. Because of the nature of remove, everything else in the ArrayList will shift left accordingly. The only thing left to do after that is add this value to the back of the ArrayList.
import java.util.ArrayList;

public class Test1
{
    public static void shiftLeftOne(ArrayList<Integer> list)
    {
        Integer firstVal = list.remove(0);
        list.add(firstVal);
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {1, 2, 3, 4, 5};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        shiftLeftOne(values);
        System.out.println("Expected Result:\t [2, 3, 4, 5, 1]");
        System.out.println("Your Result:\t\t " + values);
    }
}

Activity 10.5.36.

Finish the method moveSmallest so that it finds the smallest value in the passed-in ArrayList list and moves it to the front of the list.
Solution.
Fill-in the for loop so that it will traverse through the entire ArrayList. The conditional should check if the current element at index i is less than the element at smallestIndex. After the for-loop has completed, the method must remove the value at smallestIndex and save it to a variable, and then add it to the front of the ArrayList
import java.util.ArrayList;

public class Test1
{
    public static void moveSmallest(ArrayList<Integer> list)
    {
        int smallestIndex = 0;
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i) < list.get(smallestIndex))
            {
                smallestIndex = i;
            }
        }
        Integer smallest = list.remove(smallestIndex);
        list.add(0, smallest);
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<Integer> values = new ArrayList<Integer>();
        int[] nums = {3, 11, 54, 7, 1, 22};
        for (int i = 0; i < nums.length; i++)
        {
            values.add(nums[i]);
        }
        moveSmallest(values);
        System.out.println("Expected Result:\t [1, 3, 11, 54, 7, 22]");
        System.out.println("Your Result:\t\t " + values);
    }
}

Activity 10.5.37.

Finish the method findLongest to find and return the longest String in the ArrayList of Strings list.
Solution.
Declare a variable to hold the longest String. Initialize it to the empty string "". Loop through all the values in the ArrayList and compare its length to the length of longest. Return longest.
import java.util.ArrayList;

public class Test1
{
    public static String findLongest(ArrayList<String> list)
    {
        String longest = "";
        for (String element : list)
        {
            if (element.length() > longest.length())
            {
                longest = element;
            }
        }
        return longest;
    }

    public static void main(String[] args)
    {
        // instantiate ArrayList and fill with Integers
        ArrayList<String> values = new ArrayList<String>();
        String[] words = {"singapore", "cattle", "metropolitan", "turnstile"};
        for (int i = 0; i < words.length; i++)
        {
            values.add(words[i]);
        }
        System.out.println("Expected Result:\t metropolitan");
        System.out.print("Your Result:\t\t ");
        System.out.println(findLongest(values));
    }
}
You have attempted of activities on this page.