ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Using the ArrayList Class in Java Programming

Updated on June 10, 2013

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

See results
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)