../_images/time907.png

7.4. ArrayList AlgorithmsΒΆ

There are standard ArrayList algorithms that utilize traversals to:

  • Insert elements

  • Delete elements

  • Determine the minimum or maximum value

  • Compute a sum, average, or mode of elements

  • Search for a particular element in the array

  • Determine if at least one element has a particular property

  • Determine if all elements have a particular property

  • Access all consecutive pairs of elements

  • Determine the presence or absence of duplicate elements

  • Determine the number of elements meeting specific criteria

  • Shift or rotate elements left or right

  • Reverse the order of the elements

Here are two common ArrayList traversal loops that can be used for these algorithms:

for (Type obj : list)
{
    if (obj ....)
        ...
}

for(int i=0; i < list.size(); i++)
{
   if (list.get(i) ....)
       ...
}

You should be able to trace through code that uses all the basic ArrayList methods like the following.

exercise Check Your Understanding

You can step through the code above by clicking on the following Example1.

You can step through the code above by clicking on the following Example2.

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.

Note

If you use add or remove inside a loop that traverses an ArrayList, you may get unexpected results because the size of the ArrayList has changed!

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.

Demonstration of parallel ArrayLists.

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!

You have attempted of activities on this page