ArrayList.contains(), size(), clear, asList(), subList(), toArray(), and isEmpty() Example in Java

Java ArrayList Example
ArrayList in Java is one of the most popular Collection classes. ArrayList is an implementation of the List interface via AbstractList abstract class and provides an ordered and an index-based way to store elements. Java ArrayList is analogous to an array, which is also index-based. In fact, ArrayList in Java is internally backed by an array, which allows them to get constant time performance for retrieving elements by index. Since an array is fixed length and you can not change their size, once created, Programmers, starts using ArrayList, when they need a dynamic way to store object, i.e. which can re-size itself. See the difference between Array and List for more differences. 

Though apart from ArrayList, there are other collection classes like Vector and LinkedList which implement the List interface and provides similar functionalities, they are slightly different. ArrayList is different to Vector in terms of synchronization and speed. Most of the methods in Vector requires a lock on Collection which makes them slow. See the difference between ArrayList and Vector more differences.

Similarly, LinkedList also implements a List interface but backed by linked list data structure rather than an array, which means no direct access to element. When you use LinkedList, you need to traverse till element to get access to 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?

Using ArrayList in Java is not tricky, it's one of the simplest Collection, which does its 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 an object into the collection.

2) You want the 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 the 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 a null object, you could get NullPointerException in Java.

5) You are not sharing this list in a multi-threaded environment. Beware, ArrayList is not synchronized, which means if multiple threads is using ArrayList same time and one thread calls the get(index) method, it could receive a totally different element, if the earlier element has been removed. This is just one of the cases, 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 class in Java for testing purposes, it just awesome for storing a bunch of objects.

ArrayList.contains(), clear(), size(), isEmpty(), asList() and subList() example

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-sizes itself by using load factor, an ArrayList resize can make adding elements slowly, as it involves creating a new array and copying objects from the old array to the new array. You retrieve objects from ArrayList, using the get(index) method. 

Remember, similar to an array, the index starts with zero. Also get() method provides constant-time performance, as it just does array access with index. For removing objects from ArrayList, you got two overloaded methods, remove(index) and remove(Object), former method removes elements by index and later by using the equals() method. 

By the way, after the 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 a 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 the object is present in List or not.

How to use ArrayList in Java? ArrayList.contains(), size(), clear, and isEmpty() Example

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

isEmpty() - My preferred way to check if ArrayList is empty in Java or not. By the way, beware to check if the List is null or not, to avoid NullPointerException. That's why it's one of Java coding best practices to return an 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 an 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
        //What would be size of ArryaList now? - ZERO
        System.out.println("How many programmers buddy? " + programmers.size());

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 a programmer's delight, whenever he needs dynamic storage. In a multithreading application, just use ArrayList with caution. If you are in doubt use synchronized List or Vector.

Related Java Programming Tutorial on ArrayList from Java67
  1. How to sort ArrayList in ascending and descending order in Java
  2. How to traverse or loop ArrayList in Java
  3. How to convert ArrayList to HashMap in Java
  4. How to initialize ArrayList in one line in Java
  5. How to use CopyOnWriteArrayList in Java

1 comment:

  1. If you are in need of a thread-safe list then you can use CopyOnWriteArrayList or synchronized ArrayList in Java, its better option because vector is no longer maintained.


Feel free to comment, ask questions if you have any doubt.