How to Use a Java ArrayList
Pinterest Stumbleupon Whatsapp
Advertisement

A Java ArrayList is a general-purpose resizeable array. It provides most of the facilities generally expected of arrays in other languages. These include: accessing elements using an index, adding, removing and updating elements, dynamic re-sizing, iterating over the elements, etc. Most of these operations have been specially tweaked for general purpose usage.

There are a few other types of “arrays” (classes that implement the List interface, to be technical) which are intended for special purposes. These include:

  • LinkedList supports fast insertion and removal at intermediate indices.
  • Vector is similar to an ArrayList but is synchronized and is suitable in place of an ArrayList for multi-threaded applications.
  • Stack supports operations for mimicking a last-in-first-out list. It extends the Vector and hence is synchronized.

ArrayList Class Hierarchy from Java Collections

These special classes are outside the scope of this article. However, you will learn how to set up and use a general-purpose Java ArrayList.

Creating an ArrayList

Creating an ArrayList is simple. An empty ArrayList can be created by using the no-arguments constructor. Here we create an empty arraylist for holding strings.

ArrayList alist = new ArrayList();

If you happen to know how many items your array list will contain, you can specify the initial capacity. This initial capacity is just a hint for memory allocation — the arraylist is not restricted to holding the specified number of items. If you know and specify the initial capacity, you might get a slight improvement in performance.

ArrayList alist = new ArrayList(20);

A new ArrayList with empty slots

Populating an ArrayList

Adding Items at the End

Populating an arraylist is quite easy. Just use the add() method to add a single item to the end of the arraylist. Here is an example:

ArrayList alist = new ArrayList();
alist.add("apple");
alist.add("banana");
alist.add("cantaloupe");
alist.add("orange");
System.out.println(alist);
# prints
[apple, banana, cantaloupe, orange]

To find how many items are there in the arraylist, use the method size().

System.out.println("Number of elements in the arraylist: " + alist.size());
# prints
Number of elements in the arraylist: 4

Adding Items to an ArrayList at the end.

Adding Items at a Specified Index

Want to add an item at an arbitrary index? Specify the index as the first argument and the item is added at that index:

alist.add(3, "grapes");
System.out.println(alist);
# prints
[apple, banana, cantaloupe, grapes, orange]

Adding a Bunch of Items

You can add items from any collection in the Java Collections Hierarchy too. An ArrayList is a specific type called List. Here is a way to construct a List from a bunch of items (using Arrays.asList()) and add it to an ArrayList.

List items = Arrays.asList("pear", "cherry");
alist.addAll(items);
System.out.println(alist);
# prints
[apple, banana, cantaloupe, grapes, orange, pear, cherry]

Of course, you can specify an index as the first argument here to add the items starting at that index.

Accessing Items

Once the items have been added to the arraylist, how do we access them again?

Accessing With an Index

If you know the item’s index, you can use the get() method to retrieve the element at that index.

String item = alist.get(2);
System.out.println("Item at index 2 is: " + item);
# prints
Item at index 2 is: cantaloupe

Finding Items

What if you don’t know the index of the item? You can use indexOf() to check if the item is present in the array and retrieve the item using the returned index.

System.out.println(alist);
int index = alist.indexOf("orange");
if ( index < 0 )
  System.out.println("Item \"orange\" not found");
else
  System.out.println("Item \"orange\" found at index " + index);
# prints
[apple, banana, cantaloupe, grapes, orange, pear, cherry]
Item "orange" found at index 4

What if the item is not present in the arraylist? The indexOf() method returns -1 when the item is not found.

index = alist.indexOf("grape");
if ( index < 0 )
  System.out.println("Item \"grape\" not found");
else
  System.out.println("Item \"grape\" found at index " + index);
# prints
Item "grape" not found

Iterating Over an ArrayList

Of course, the most common usage of an ArrayList is iterating over the elements. This can be accomplished in a number of ways. We show a couple of simple ones here.

Here is the simplest way of iterating over an arraylist and extracting the items for some kind of processing.

for (String fruit : alist) {
  System.out.println("Found fruit \"" + fruit + "\"");
}
# prints
Found fruit "apple"
Found fruit "banana"
Found fruit "cantaloupe"
Found fruit "grapes"
Found fruit "orange"
Found fruit "pear"
Found fruit "cherry"

This code uses the Java Enhanced For-Loop which was introduced in Java 1.5. Before that, you could iterate over the items with an iterator. An iterator is also used when you need to remove elements during the process of iteration as the example below illustrates. (Note that we make a copy of the arraylist and work on the copy.)

ArrayList blist = new ArrayList(alist);
for (Iterator iter = blist.iterator() ; iter.hasNext() ; ) {
  String fruit = iter.next();
  if ( fruit.startsWith("c") )
    iter.remove();
  else
    System.out.println("Keeping \"" + fruit + "\"");
}
# prints
Keeping "apple"
Keeping "banana"
Keeping "grapes"
Keeping "orange"
Keeping "pear"

Replacing Items

Once items are added, we need a way to replace unwanted items. That can be done by using the set() method with an index.

alist.set(5, "pineapple");
System.out.println(alist);
# prints
[apple, banana, cantaloupe, grapes, orange, pineapple, cherry]

Removing Items

Let us now see how we can remove items from an arraylist. If you know the index of the item (perhaps you used indexOf() described above), you can use the remove() method with the index. It returns the removed element.

String fruit = alist.remove(2);
System.out.println("Removed element at 2: " + fruit);
# prints
Removed element at 2: cantaloupe

You can also specify the element to remove the first occurrence of the element in the list. The method returns true if the element was found and removed.

fruit = "grapes";
System.out.println("Remove " +fruit+ " from the list? " + alist.remove(fruit));
# prints
Remove grapes from the list? true

How are you using the ArrayList in your projects and what special issues have you faced? Please let us know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Evan
    July 14, 2017 at 9:36 am

    Would this even compile? You haven't typed the ArrayList and you don't cast the results of get.

    • Jay Sridhar
      August 5, 2017 at 7:19 am

      The blogging system "auto-corrected" the code related to specialization of generics.