Friday, March 1, 2013

Java ArrayList Tutorial and Examples - Developers Guide

ArrayList in Java is one of the most popular Collection class. ArrayList is an implementation of List interface via AbstractList abstract class, and provides ordered and index based way to store elements. Java ArrayList is analogous to array, which is also index based. In fact, ArrayList in Java is internally backed by array, which allows them to get constant time performance for retrieving elements by index. Since array is fixed length and you can not change there size, once created, Programmers, starts using ArrayList, when they need a dynamic way to store object, i.e. which can re-size itself. See difference between Array and List for more differences. Though, apart from ArrayList, there are other collection classes like Vector and LinkedList which implements List interface and provides similar functionalities, but they are slightly different. ArrayList is different to Vector in terms of synchronization and speed. Most of methods in Vector requires lock on Collection which makes them slow. By the way you can see difference between ArrayList and Vector more differences. Similarly, LinkedList also implements List interface but backed by linked list data structure rather than array, which means no direct access to element. When you use LinkedList, you need to traverse till element to get access of it. Apart from that, there are couple of more differences, which you can check on difference between ArrayList vs LinkedList post. In this Java programming tutorial, we will learn How to use ArrayList in Java i.e. adding, removing, accessing objects from ArrayList and  learning key details.

When to use ArrayList in Java

ArrayList in Java Tutorial programming example How to
Using ArrayList in Java is not tricky, it's one of the simplest Collection, which does it job brilliant. It's you, who needs to decide when to use ArrayList or LinkedList, or another implementation of Vector. You should be using ArrayList in Java :

1) When you need to maintain insertion order of elements i.e. the order on which you insert object into collection.

2) You want fastest access of element by index. get(index) return object from ArrayList with O(1) time, also known as constant time.

3) You don't mind duplicates. Like any other List implementation, ArrayList also allows duplicates, you can add same object multiple times in ArrayList.

4) You don't mind null elements. ArrayList is fine, if you add null objects on it but beware of calling methods on null object, you could get NullPointerException in Java.

5) You are not sharing this list in multi-threaded environment. Beware, ArrayList is not synchronized, which means if multiple thread is using ArrayList same time and one thread calls get(index) method, it could receive a totally different element, if earlier element has been removed. This is just one of the case, there could be many multi-threading issues, if you share ArrayList without proper synchronization.

Having said that, Java ArrayList is my default choice when it comes to use Collection for testing purpose, it just awesome for storing bunch of objects.

How to use ArrayList in Java

In this section, we will see How to add objects, access objects and remove objects from ArrayList. add() method also provides constant time performance, if it doesn't trigger resizing. Since ArrayList re-size itself by using load factor, an ArrayList resize can make adding elements slowly, as it involves creating new array and copying objects from old array to new array. You retrieve objects form ArrayList, using get(index) method. Remember, similar to array, index starts with zero. Also get() method provides constant time performance, as it just do array access with index. For removing objects from ArrayList, you got two overloaded methods, remove(index) and remove(Object), former method removes element by index and later by using equals() method. By the way, after introduction of autoboxing in Java 5, this turns out to a confusing way to overload methods in Java, considering you can store Integer object in ArrayList, which can also be index. See Java best practices to overload method for more information. Apart from basics, add(), get(), and remove() operations, here are couple of more methods from Java ArrayList which is worth knowing :

clear() - Removes all elements from ArrayList in Java. An easy way to empty ArrayList in Java. List can also be reused after clearing it.

size() -  Returns number of objects or elements stored in Java ArrayList. This is another way to check if List is empty or not.

contains(Object o) - pretty useful method to check if an Object exists in Java ArrayList or not. contains() internally use equals() method to check if object is present in List or not.

indexOf(Object o) - Another utility method which returns index of a particular object. This method got a twin brother lastIndexOf(Object o), which returns index of last occurrence.

isEmpty() - My preferred way to check if ArrayList is empty in Java or not. By the way, beware to check if List is null or not, to avoid NullPointerException. That's why it's one of Java coding best practice to return empty List, instead of returning null.

toArray() - Utility method to convert ArrayList into Array in Java, by the way there are couple of more ways to get array from Java ArrayList, see here for all those ways.

subList(startIdx, endIdx) - One way to create sub List in Java. Sub List will contain elements from start index to end index. See this article for complete example of getting sublist from ArrayList in Java.

Java ArrayList Example

Now, enough with theory. Let' see them in action with this ArrayList example in Java :

import java.util.ArrayList;

/**
 * Java program to show How to use ArrayList in Java. This examples teaches,
 * how to add objects, remove object, and access object from Java ArrayList.
 * Along with, using contains(), clear() and size() method of ArrayList.
 * @author Java67
 */
public class StringReplace {

    public static void main(String args[]) {
     
        ArrayList<String> programmers = new ArrayList<String>();
       
        //adding objects into ArrayList, here we have added String
        programmers.add("James Gosling");
        programmers.add("Dennis Ritchie");
        programmers.add("Ken Thomson");
        programmers.add("Bjarne Stroustrup");
       
        //Now, size of this List should be 4 - No?
        System.out.println("How many programmers? " + programmers.size());
       
        //Let's get first programmer, remember index starts with zero
        System.out.println("Who is the first programmer in our List? " + programmers.get(0));
       
        //Let's remove last programmer from our list
        programmers.remove(programmers.size() -1);
       
        //Now, size should be 3 - Right?
        System.out.println("How many programmers remaining? " + programmers.size());
       
        //Let's check if our List contains Dennis Ritchie, inventor of C
        boolean doYouGotRitchie = programmers.contains("Dennis Ritchie");
        System.out.println("Do you have the great Dennis Ritchie in your List : " + doYouGotRitchie);
       
        //How about checking if Rod Johnson is in list or not
        System.out.println("Do you got Rod Johnson, creator of Spring framework : " + programmers.contains("Rod Johnson"));

       
        //Now it's time to shake break, let's clear ArrayList before we go
        programmers.clear();
       
        //What would be size of ArryaList now? - ZERO
        System.out.println("How many programmers buddy? " + programmers.size());
 
     
    }
}

Output:
How many programmers? 4
Who is the first programmer in our List? James Gosling
How many programmers remaining? 3
Do you have the great Dennis Ritchie in your List : true
Do you got Rod Johnson, creator of Spring framework : false
How many programmers buddy? 0

That's all about ArrayList in Java. We have seen lots of Java ArrayList examples and  learned when to use ArrayList in Java and How to add, remove, and access objects from Java ArrayList. As I said before, this collection is programmer's delight, whenever he needs a dynamic storage. In multithreading application, just use ArrayList with caution. If you are in doubt use synchronized List or Vector.


Related Java Programming Tutorial on Array List from Java67

No comments:

Post a Comment

Java67 Headline Animator