arraylist in java

ArrayList in Java: Understand With Example

ArrayList is undoubtedly of the most essential data structure in Java. You might be just starting out with the ArrayList in Java after learning about Arrays. Here let us learn about ArrayList in Java with example. Let us being our step by step guide to understanding ArrayList.

This post is going to cover almost all aspects of the ArrayList for a basic requirement. Feel free to skip to pars using the table of contents.

What is ArrayList in Java ?

It is one implementation of List interface in Java. List itself is one of the common Collection in Java. The List interface is implemented to be used like an Array. But unlike an array ArrayList can be dynamically resized at runtime.

Using ArrayList is much more convenient than the Array. As the manipulation of data becomes much more flexible and easy.

It is worth noting that the primitive data types cannot be used and their Class counterpart must be used. Like Integer for int, Float for float and so on. Now we have understood about the ArrayList in brief let us see how we can use the ArrayList.

When to use ArrayList in Java ?

If you are just starting with Java you might be wondering when should I really use a ArrayList ? The answer is that it depends.

If you understand Arrays well enough you must start using ArrayList for your day to day tasks. Maybe in Android development of Web Development.

But generally if you are doing some business problem solving. You might want to structure your data in an easily accessible way. In that case you must use the ArrayList.

However if you are writing the next gen algorithm that solves world’s hunger problem. You might be better off using a more traditional approach i.e using Array.

Once you get more comfortable with programming you will start to see pattern. Which will make you understand what to use in which situation.

That being said let us start our ArrayList.

Also Read : Learn to Implement Run Length Encoding in Java

TECHENUM

Declaring and initializing ArrayList

The syntax for declaration and initialization is pretty straight forward. Let’s look at it below.

ArrayList<String> myListOfStrings = new ArrayList<String>();Code language: Java (java)

And if you want to pass a size for the ArrayList you can do that by simply as

ArrayList<String> myListOfStrings = new ArrayList<String>(32);Code language: Java (java)

The 32 in the above snippet is the initial capacity. Which is useless most of the time as the array size is automatically adjusted based on the number of items.

Basic operations in ArrayList

Now that we know how to declare and initialize ArrayList. Let us see how we can add new Strings and access the stored Strings.

Add ( .add() )

For adding items to our ArrayList we can use .add() method. Let us see an example.

ArrayList<String> myListOfStrings = new ArrayList<String>();
// this line adds the String #1 to the List
myListOfStrings.add("String #1");
// Add another value to the List
myListOfStrings.add("Another value");Code language: JavaScript (javascript)

But what if you wanted to add item at specific index ?

We have a solution. Use the .add(index, value) method.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("String #1");
myListOfStrings.add("Another Value");
// add this value to first index
myListOfStrings.add(0, "My First value.");Code language: Java (java)

Update / Replace ( .set() )

If you want to update the value at specified index you can use the .set() method. Let us look at an example

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("String #1");
myListOfStrings.add("Another Value");
// replace the first item with new value
myListOfStrings.set(0, "My First value.");Code language: JavaScript (javascript)

Accessing ( .get() )

How can you access the stored value ? Well let us see we have to use the .get() method provided to us.

You can use it as

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");
// we will have Value #3 because index starts at 0
String valueAtTwo = myListOfStrings.get(2);Code language: Java (java)

Remove ( .remove() )

Now let us see how we can replace the value of our ArrayList.

You can remove value from ArrayList in two ways. One is by passing the object another is using the index of the value in the ArrayList.

Deleting item by passing object.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("String #1");
myListOfStrings.add("Another Value");
myListOfStrings.add("Another Value");
// remove the value at index 1
myListOfStrings.remove(1);Code language: Java (java)

We can also pass in the same value to remove it from the ArrayList.

// Example to pass in the reference and remove this item
String value1 = "String #1";
ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add(value1);
myListOfStrings.add("Another Value");
// remove value by reference
myListOfStrings.remove(value1);Code language: Java (java)

See that I have use the same reference value passed to remove that element from the ArrayList.

Check if empty ( .isEmpty() )

Let us check if the ArrayList is empty or it has some number of value. Use the .isEmpty() method to find if the values.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

// false in this example but true if there are no items
boolean isMyListOfStringsEmpty = myListOfStrings.isEmpty();Code language: JavaScript (javascript)

Removing all items ( .clear() )

You can remove all the items from the ArrayList without having to put much effort.

Use the .clear() method and the values will be removed. An example is given below

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

// will remove everything from the list
myListOfStrings.clear();Code language: Java (java)

Check a value ( .contains() )

Check if a value exist in the ArrayList very easily with the use of .contains(). Let us see an example

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

boolean hasMySearchValue = myListOfStrings.contains("Value #2");Code language: Java (java)

Index of value ( .indexOf() )

What if we need the index of the item in the ArrayList ? You can just use the .indexOf() method to get the position.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

int indexOfMyValue = myListOfStrings.indexOf("Value #2");Code language: Java (java)

It is worth noting that if no match was found the method will return -1.

The size of the ArrayList

Like in Array you have a simple way of knowing the size of the ArrayList. We use .size() method to get the total number of items in the ArrayList.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

// value of total items will be 4
int totalItems = myListOfStrings.size();Code language: Java (java)

Those were some basic example of ArrayList usage in Java.

Also Read : 3 Essential Datastructures in Object Oriented Programming

TECHENUM

Iterating each element of ArrayList

You might want to loop through each of the elements in the ArrayList. There are multiple ways you can do that. Here I have listed the example of using loop in ArrayList in Java.

Using foreach ( if you don’t want index )

Let us see if you want to quickly iterate through the items of the ArrayList. Index is not provided by foreach so you do not know the current item’s position.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

// using foreach
for (String value : myListOfStrings) {
    System.out.println(value);
}Code language: Java (java)

Using the Iterator interface

You can also use the Iterator interface to loop through each items in the ArrayList. This is not preferred over the foreach method but it is possible to do so.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

Iterator<String> iterator = myListOfStrings.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}Code language: Java (java)

The iterator has multiple methods to determine if there are more elements .hasNext(). The while loop continues to run until the iterator reaches final element.

You can get element using .next() method.

Using for loop ( when you want index )

If you want the index of each item for some reason. Then you can use the for loop to access both the index and value of ArrayList.

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

for (int index = 0; index < myListOfStrings.size() - 1; index++) {
    String value = myListOfStrings.get(index);
    System.out.println(value);
}Code language: Java (java)

We have to set our exit condition as myListOfStrings.size() - 1 because indexing starts at 0.

Also Read : 7 Sites to Learn Programming Languages Online For Free

TECHENUM

Creating a sub list

You can create a new List with the items from the current ArrayList. If you only wanted some elements you do not need to run a loop and then create another List and add items to it.

You can just use the method .subList() to produce the new list. All you have to do is provide the start index and end index. The value at starting index in included but the value at end index is excluded.

Let us see an example

ArrayList<String> myListOfStrings = new ArrayList<String>();
myListOfStrings.add("Value #1");
myListOfStrings.add("Value #2");
myListOfStrings.add("Value #3");
myListOfStrings.add("Value #4");

// will have items at 0 and 1 
List<String> myNewList = myListOfStrings.subList(0, 2);Code language: Java (java)

The resulting values are not ArrayList but only List. You can create a new ArrayList with the result if you like.

That was it about the ArrayList hope you know know how to do basic things using the ArrayList implementation of List interface. It was only a basic example of ArrayList in Java.

Related Posts

One thought on “ArrayList in Java: Understand With Example

  1. Pingback: Android Fingerprint Authentication Tutorial: How to Guide - techenum

Comments are closed.