Home » Core Java » util » ArrayList » Arraylist in Java Example – How to use arraylist

About Konstantina Dimtsa

Konstantina Dimtsa
Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Arraylist in Java Example – How to use arraylist

In this example we will show how to use ArrayList in Java. The class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list. It implements the List interface.

A major question related to arraylists is about when to use arraylists instead of arrays and vice versa. An ArrayList is a dynamic data structure so it can be used when there is no upper bound on the number of elements.

From the other side, a simple Array in java is a static data structure, because the initial size of array cannot be changed, so it can be used only when the data has a known number of elements.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

1.ArrayList Constructors

The ArrayList class supports three constructors.

  • Arraylist()

This constructor builds an empty list.

  • ArrayList(Collection<? extends E> c)

This constructor creates a list containing the elements of the specified collection. Note that E is the notation for the type of an element in a collection.

  • ArrayList(int initialCapacity)

This constructor creates an empty list with the specified initial capacity.

For example, if you want to create an empty array list of Strings then you would do the following:

ArrayList<String> list = new ArrayList<String>();

If you want to create an array list with initial capacity, then you should do the following:

ArrayList<Integer> list = new ArrayList<Integer>(7);

Note that ArrayList class supports only object types and not primitive types.

2. ArrayList common methods

Here are some of the most useful ArrayList methods.

  • Adding elements to the list
    • boolean add(Element e)
      Adds the specified element to the end of this list.
    • void add(int index, Element e)
      Adds the specified element at the specified position in the list.
  • Removing elements from the list
    • void clear()
      Removes all the elements from the list.
    • E remove(int index)
      Removes the element at the specified position in the list.
    • protected void removeRange(int start, int end)
      Removes from the list all the elements starting from index start (included) until index end (not included).
  • Getting elements from the list
    • E get(int index)
      Returns the element at the specified position.
    • Object[] toArray()
      Returns an array containing all the elements of the list in proper sequence.
  • Setting an element
    • E set(int index, E element)
      Replaces the element at the specified position with the specified element.
  • Searching elements
    • boolean contains(Object o)
      Returns true if the specified element is found in the list.
    • int indexOf(Object o)
      Returns the index of the first occurrence of the specified element in the list. If this element is not in the list, the method returns -1.
    • int lastIndexOf(Object o)
      Returns the index of the last occurrence of the specified element in the list. If this element is not in the list, the method returns -1.
  • Iterating the arraylist
    • Iterator iterator()
      Returns an iterator over the elements in the list.
    • ListIterator listIterator()
      Returns a list iterator over the elements in this list.
  • Checking if the list is empty
    • boolean isEmpty()
      Returns true if the list does not contain any element.
  • Getting the size of the list
    • int size()
      Returns the length of the list (the number of elements contained in the list).

Those were the most commonly used methods of java.util.ArrayList. For further details for each method or for other methods that are not mentioned in this section, you can have a look at official java api.

3. Examples of using ArrayList in Java

Create a java class named ArrayListExamples.java with the following code:

ArrayListExamples.java

import java.util.*;

public class ArrayListExamples {

	public static void main(String args[]) {
		// Creating an empty array list
		ArrayList<String> list = new ArrayList<String>();

		// Adding items to arrayList
		list.add("Item1");
		list.add("Item2");
		list.add(2, "Item3"); // it will add Item3 to the third position of
								// array list
		list.add("Item4");

		// Display the contents of the array list
		System.out.println("The arraylist contains the following elements: "
				+ list);

		// Checking index of an item
		int pos = list.indexOf("Item2");
		System.out.println("The index of Item2 is: " + pos);

		// Checking if array list is empty
		boolean check = list.isEmpty();
		System.out.println("Checking if the arraylist is empty: " + check);

		// Getting the size of the list
		int size = list.size();
		System.out.println("The size of the list is: " + size);

		// Checking if an element is included to the list
		boolean element = list.contains("Item5");
		System.out
				.println("Checking if the arraylist contains the object Item5: "
						+ element);

		// Getting the element in a specific position
		String item = list.get(0);
		System.out.println("The item is the index 0 is: " + item);

		// Retrieve elements from the arraylist

		// 1st way: loop using index and size list
		System.out
				.println("Retrieving items with loop using index and size list");
		for (int i = 0; i < list.size(); i++) {
			System.out.println("Index: " + i + " - Item: " + list.get(i));
		}

		// 2nd way:using foreach loop
		System.out.println("Retrieving items using foreach loop");
		for (String str : list) {
			System.out.println("Item is: " + str);
		}

		// 3rd way:using iterator
		// hasNext(): returns true if there are more elements
		// next(): returns the next element
		System.out.println("Retrieving items using iterator");
		for (Iterator<String> it = list.iterator(); it.hasNext();) {
			System.out.println("Item is: " + it.next());
		}

		// Replacing an element
		list.set(1, "NewItem");
		System.out.println("The arraylist after the replacement is: " + list);

		// Removing items
		// removing the item in index 0
		list.remove(0);

		// removing the first occurrence of item "Item3"
		list.remove("Item3");

		System.out.println("The final contents of the arraylist are: " + list);

		// Converting ArrayList to Array
		String[] simpleArray = list.toArray(new String[list.size()]);
		System.out.println("The array created after the conversion of our arraylist is: "
						+ Arrays.toString(simpleArray));
	}
}

In the above code, we can see that many ArrayList usage cases are covered. Adding elements to the list using 2 different methods, removing elements, getting the size of the list, checking if the list is empty, checking if a specific element is contained to the list. Also, 3 different ways are presented for retrieving the elements of a list. Finally, we show how to convert an ArrayList to Array.

  • Output:
The arraylist contains the following elements: [Item1, Item2, Item3, Item4]
The index of Item2 is: 1
Checking if the arraylist is empty: false
The size of the list is: 4
Checking if the arraylist contains the object Item5: false
The item is the index 0 is: Item1
Retrieving items with loop using index and size list
Index: 0 - Item: Item1
Index: 1 - Item: Item2
Index: 2 - Item: Item3
Index: 3 - Item: Item4
Retrieving items using foreach loop
Item is: Item1
Item is: Item2
Item is: Item3
Item is: Item4
Retrieving items using iterator
Item is: Item1
Item is: Item2
Item is: Item3
Item is: Item4
The arraylist after the replacement is: [Item1, NewItem, Item3, Item4]
The final contents of the arraylist are: [NewItem, Item4]
The array created after the conversion of our arraylist is: [NewItem, Item4]

As we see in the output, the results are complied with what we described in the previous section.

4. Download the source code

This was an example of using ArrayList in Java. Download the source code here: ArrayListExample.zip

Don’t forget to check out our Academy premium site for advanced Java training!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

 

Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns