Using the ArrayList Class in Java Programming

Introduction to the ArrayList Class in Java

The ArrayList class builds on the basic array type that is implemented in most modern programming languages, In this tutorial we introduce the ArrayList class that is part of the Java programming language. Java has become extremely popular for application development and also for embedded systems such as wireless telephones. The Android Operating System is programmed in Java and also supports 'apps' written in Java. Undoubtedly, many apps make use of the ArrayList class, making this data structure an important tool for developers who hope to write the next world-famous application for Android phones.

A traditional array in a modern programming language can be leveraged to manage a list of homogeneous data items. While this data structure is useful for many applications, it does have a few shortcomings:

  • An array cannot be dynamically re-sized
  • An array does not include native searching and sorting functionality
  • An array does not support in-place deletion of data items.

Of course, we are speaking in general terms. A competent programmer could easily build a wrapper class around a traditional array data structure for the purpose of implementing the features described in the  above list. Instead of going to this trouble (re-inventing the wheel) we introduce a Java class that implements the above list and is a part of the Java SE distribution.

Getting Started

In order to use the ArrayList class, the proper package should be imported:

// Import the package that contains the ArrayList class
import java.util.*;

Next, we declare a reference to an object of type ArrayList:

//Declare the reference to the object
ArrayList<Integer> myArrayList;

Next, we attempt to instantiate the object and assign it to our reference:

//Instantiate the object
myArrayList = new ArrayList<Integer>();

At this point it would be interesting to learn the size of our object. All data types have some default implicit size associated with their instance. We have not explicitly added anything to the collection of integers, but Java may have arbitrarily created a few 'buckets' by default. Perhaps the default constructor is programmed to assume that something will be added to the data structure. This is a reasonable assumption and will almost certainly result in a performance increase relative to creating an 'empty' ArrayList object. It would be a rare program that instantiated an ArrayList object with the intention of leaving it empty.

Here is simple code to print out the size (in elements) of the ArrayList object:

// Query the current size of the object.
System.out.println("Size of ArrayList = " + myArrayList.size());

The output of the program at this point would be

Size of ArrayList = 0

We observer that the ArrayList object was instantiated with zero elements. Java is ostensibly universally portable, but this little test is to simple to implement that we encourage the reader to manually verify our results on their target hardware/software platform.

Adding Items to the End of the ArrayList

Next, we demonstrate how to add elements to the end of the object. The following code illustrates this:

//==============================
//Basic ArrayList operations:
//==============================
//Add an item
myArrayList.add(42);
//Add another item
myArrayList.add(43);

We have added 2 integers to the collection. If we print the size of the object now, we get:

Size of ArrayList = 2


Lest any confusion arise, the 'size' value is not to be interpreted as a number of bytes or any other metric that relates to memory footprint. This value simply represents the number of elements in the collection.

Looping

Next, we use a 'for' loop to add a relatively large number of elements to the object:

//Add a lot of items to the object.
int i;
for (i = 0; i < 100; i++) {
	myArrayList.add(i); // Add the item to the end of the list.
}

Searching Through the ArrayList

One very useful feature of an ArrayList object that is not supported by a traditional array data item is the capability to search through the data structure for a particular value. In the following code fragment we illustrate this feature:

//Search for an item with value 43.
int idx;
idx = myArrayList.indexOf(43);
System.out.println("Element with value 43 is at index " + idx);

The above code fragment searches through an ArrayList object for the integer value 43. The index of the first occurrence of the requested value is returned from the method call. Searching begins at the first (zeroth) element in this example.

If the search fails, an invalid index value, -1, is returned. The following code snippet illustrates this:

//Search for an item with value 999. We know it's not there.
idx = myArrayList.indexOf(999);
System.out.println("Element with value 999 is at index " + idx);

Accessing Values by Index

Like a traditional array, an ArrayList object supports indexing. The syntax is a little different than the square brackets that are common in many programming languages:

When reading the following code snippet, keep in mind that indexing begins at zero rather than 1. The zeroth element is the first element in the collection. 

//Access an item at a specific index.
System.out.println("Element at index 6 is " + myArrayList.get(6));

Using an Iterator Object

Our final example describes how to use an iterator object to step through the collection. The iterator object is a very simple type that should type-converted into a useful value through the application of a method that belongs to the Integer class.

//Enumerate the elements with an iterator object.
Iterator myIterator = myArrayList.iterator();
while (myIterator.hasNext()) {
    Object x;
    x = myIterator.next(); // next() returns an object, not an int
    sum += Integer.parseInt(x.toString());  // What a mess. Must be an easier way.
}
System.out.println("Sum of elements is " + sum);

Conclusion

The ArrayList class is a useful data structure that is part of Java SE. It adds useful functionality to the common array type that is found in most modern programming languages.


A working class follows. This class contains all the examples described above.

// Import the util package (namespace), which contains the definition of the ArrayList template
import java.util.*;

/**
 *
 * @author nicomp
 */
public class CollectionDemo {
/**
 * A demonstration of the ArrayList class
 */
    public static void DemonstrateTheArrayList() {
        System.out.println("CollectionDemo.DemonstrateTheArrayList()");

        int i, idx, sum = 0;

//      Declare the reference to the object
        ArrayList<Integer> myArrayList;

//      Instantiate the object
        myArrayList = new ArrayList<Integer>();

//      Query the current size of the object before we add anything.
        System.out.println("Size of ArrayList = " + myArrayList.size());

        //      ==============================
//      Basic ArrayList operations:
//      ==============================
//      Add an item
        myArrayList.add(42);
//      Add another item
        myArrayList.add(43);

//      Query the current size of the object.
        System.out.println("Size of ArrayList = " + myArrayList.size());

//      Add a lot of items to the object.
        for (i = 0; i < 100; i++) {
            myArrayList.add(i); // Add the item to the end of the list.
        }
//      Search for an item with value 43.
        idx = myArrayList.indexOf(43);
        System.out.println("Element with value 43 is at index " + idx);

//      Search for an item with value 999. We know it's not there.
        idx = myArrayList.indexOf(999);
        System.out.println("Element with value 999 is at index " + idx);

//      Acess an item at a specific index.
        System.out.println("Element at index 6 is " + myArrayList.get(6));

//      Enumerate the elements with an iterator object.
        Iterator myIterator = myArrayList.iterator();
        while (myIterator.hasNext()) {
            Object x;
            x = myIterator.next();                  // next() returns an object, not an int
            sum += Integer.parseInt(x.toString());  // What a mess. Must be an easier way.
        }
        System.out.println("Sum of elements is " + sum);

    }
}

Take this poll so more people will get to see this article

I use ArrayList objects in my Java Code

  • Yes
  • No
  • I will start using them after reading this stellar article
  • I don't program in Java, but if I did I would defintely use ArrayList objects
See results without voting

More by this Author


Comments 6 comments

callisto123 profile image

callisto123 5 years ago

Java always reminds me of a combination of VB and C for some reason! One day I'll get around to learning it, code looks fairly straight forward; nicely written!


drbj profile image

drbj 5 years ago from south Florida

niconmp - ???????????? (translation: I think I'm in a parallel universe.) :)


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@callisto123 : That is an apt description. Thank you for your kind words.

@drbj : Indeed, Java is useful for parallel programming. I

will begin work on that hub.


drbj profile image

drbj 5 years ago from south Florida

That's exactly what I was afraid of!!!


Java Programs profile image

Java Programs 4 years ago from India

Very informative hub about ArrayLists .... Highly used collection in java


nicomp profile image

nicomp 3 years ago from Ohio, USA Author

I don't understand why the HubLords deprecated this hub: I guess it needs a poll or a video or some flashy graphics. Sigh.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working