8.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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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.

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.

You have attempted 1 of 5 activities on this page