How to use ArrayList in Java with Example Programs

How to use ArrayList in Java with Example Programs

Java ArrayList is a dynamic array with resizable-array implementation of Java List interface. In the tutorial, we will learn how to use Java ArrayList by examples:

  • What is Java ArrayList?
  • How to construct a Java ArrayList?
  • Do a Set Operations with Java ArrayList
  • How to Sort Java ArrayList?
  • Use Java ArrayList with Multi-Thread Environment

Related posts:
How to use Java Stack with Examples
How to use Java PriorityQueue with Examples

Java ArrayList

– Java ArrayList is resizable-array implementation of Java List interface.
+ When adding new elements, Java ArrayList grows its size automatically.
+ When the elements are removed, Java ArrayList shrinks the size.

– Java ArrayList permits all elements, including null. But Java ArrayList can NOT contain primative elements such int, boolean, char… Java ArrayList can contains object elements like: Integer, String, Boolean…, or User Defined Objects.
– Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. For reducing the amount of incremental reallocation, we can increase the capacity of an ArrayList instance before adding a large number of elements.
– The ArrayList implementation is not synchronized. To prevent accidental unsynchronized access to the list, we use the solution:

List list = Collections.synchronizedList(new ArrayList(...));

Here is the hierarchy of Java ArrayList:

How to use ArrayList in Java with Example Programs - hierarchy

How to Initialize ArrayList in Java with Examples

– To construct an empty Java Arraylist, we can use the below constructor:

public ArrayList()

Example:

– We can construct a Java ArrayList that contains the elements of the specified collection with following constructor:

public ArrayList(Collection c)

-> It throws NullPointerException if the specified collection is null.

Example:

How to Add an Element to Java ArrayList with Examples

– To add an element to an Java ArrayList, we can use the add method:

public boolean add(E e)

-> It appends a specified element to the end of the Java ArrayList.

Examples:

– We can insert the specified element at the specified position in an Java ArrayList with following add signature method:

public void add(int index, E element)

It shifts the element currently at that position (if any) and any subsequent elements to the right.

There are 2 parameters in above signature:

  • index: is the position which the specified element is to be inserted
  • element: the item to be inserted

If the index is out of the range, the above add method will throw IndexOutOfBoundsException.

Example:

How to Add a Collection to Java ArrayList with Examples

We can add a Collection to a Java ArrayList with addAll method:

addAll(int index, Collection c)

-> It helps to append all of the elements in the specified collection to the end of Java ArrayList.
If the specified collection is null, a NullPointerException will be throwed.

Example:

We also can insert all of the elements in the specified collection into the Java ArrayList, and starting at the specified position by using following addAll signature method:

public boolean addAll(int index, Collection c)

It throws exceptions when:

  • if the index is out of range (index < 0 || index > size()), throws IndexOutOfBoundsException
  • if the specified collection is null, throws NullPointerException

Example:

How to Iterate Through ArrayList in Java with Examples

To iterate through a Java ArrayList, we can use one of the following solution:

  • Use an normal Loop statement to travel through Java ArrayList
  • Use the Loop statement with index to iterate through Java ArrayList
  • Use forEch method
  • Use iterator() method
  • Combine iterator() method and forEachRemaining() method
  • Use the listIterator() to traverse backwards Java ArrayList
  • Use Java Stream to iterate through a Java ArrayList

– We just use an normal loop solution to travel through Java ArrayList as following example:

– We use the loop statement with index to iterate through Java ArrayList:

– We can use forEch method:

public void forEach(Consumer action)

-> It performs the given action for each element of the Iterable.

Example:

– We can use iterator() method:

public Iterator iterator()

-> The method returns an iterator over the elements in the Arraylist in proper sequence.

Example:

– We can combine iterator() method and forEachRemaining() method to travel through Java ArrayList:

– We also can use the listIterator() to to traverse backwards Java ArrayList:

ListIterator listIterator();

Example:

– We can use Java Stream to iterate through a Java ArrayList:

How to Get/Set Elements in Java ArrayList with Examples

We can get/set Java ArrayList elements by get() and set() methods:

– Get method signature:

public E get(int index)
-> index: index of the element to return
-> if the index is out of range, IndexOutOfBoundsException will be throwed.

Example:

– Set method signature:

public E set(int index, E element)

-> if the index is out of range, IndexOutOfBoundsException will be throwed.

Example:

-> Output:

How to Remove Elements in Java ArrayList with Examples

We have a set of operations to remove element in Java ArrayList:

  • Removes the element at the specified position.
  • Removes the first occurrence of the specified element.
  • Removes all of its elements from the Java ArrayList that are contained in the specified collection.
  • Removes all of the elements of the Java ArrayList that pass the given predicate.
  • Removes all of the elements from the Java ArrayList.

How to Removes Element at the Specified Position Examples?

– We use the method: public E remove(int index)
-> It removes the element at the specified position and shifts any subsequent elements to the left.
-> if the index is out of the range, IndexOutOfBoundsException will be throwed.

Example:

How to removes the first occurrence of the specified element?
– We use the method signature:

public boolean remove(Object o)

-> Removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i)))

Example:

How to removes all elements from Java ArrayList that are contained in the specified collection?

-> We use the below method signature:
public boolean removeAll(Collection c)

The above will throw 2 exceptions:

  • ClassCastException: if the class of an element of the Java ArrayList is incompatible with the specified collection
  • NullPointerException: if this Java ArrayList contains a null element and the specified collection does not permit null elements, or if the specified collection is null

Example:

How to removes all of the elements of the Java ArrayList that pass the given Predicate?
-> We can use the below method signature:

removeIf(Predicate filter)

filter: a predicate which returns true for elements to be removed.

Example:

How to removes all of the elements from the Java ArrayList?
-> We use clear() method:

public void clear()

– It removes all of the elements from the Java ArrayList.

Example:

How to Search an Element in Java ArrayList with Examples

To find out an element in Java ArrayList, we can use two methods:

  • indexOf
  • lastIndexOf

indexOf method:

public int indexOf(Object o)

-> Returns the index of the first occurrence of the specified element in this list.
-> Or -1 if this list does not contain the element.

Example:

lastIndexOf signature method:

public int lastIndexOf(Object o)

-> Returns the index of the last occurrence of the specified element in this list
-> or -1 if this list does not contain the element

Example:

How to Get a View from Java ArrayList with Examples

We use subList to get a view of the portion of the Java ArrayList between the specified fromIndex, inclusive, and toIndex, exclusive.

– Method Signature:

public List subList(int fromIndex, int toIndex)

It may be throw Exceptions:

  • IndexOutOfBoundsException will be throwed if fromIndex < 0 || toIndex > size
  • IllegalArgumentException will be throwed if fromIndex > toIndex

Example:

How to Create Java ArrayList of Custom Objects with Examples

Now We create a Java ArrayList with Custom User defined Object,

– Create Developer class:

– Create Developer Java ArrayList:

– Implement equals method in Developer class for comparing objects:

– Now we can find a Developer as below code:

How to Sort ArrayList in Java with Examples

We have 2 solution for sorting Java ArrayList:

  • Using the method void sort(Comparator c) of a Java ArrayList instance
  • Using the method void sort(List list, Comparator c) of Collection interface

Let’s do details!

– Using the sort() method of an ArrayList instance:

public void sort(Comparator c)

-> It sorts the ArrayList according to the order induced by the specified Comparator.

Example:

– In the following example, we define a Comparator for sorting a String ArrayList by the length:

– Now We use Collection.sort() method for sorting:

public static void sort(List list, Comparator c)

+ Example Sorting Integer Java ArrayList using Collections.sort():

+ Example Sorting String Java ArrayList using Collection.sort():

+ Example Sorting User Custom Defined Object by Salary property using Collection.sort():

How to Synchronize ArrayList in Java with Examples

As we know, the Java ArrayList implementation is not synchronized. So we can try to simulate a multi-thread environment to prove it.

– Example:

-> Output:

In above example, we create a multi-thread environment with 20 threads and submit 200 tasks to process. Each task just does a simple work: incrementing each element of the ArrayList by one.
So the expected output should be [200, 200]. But NOT right, the real output is non-deterministic for each running time, such as [194, 200] or [198, 199]…

Why?
-> Beacause each Thread might overrides the changes of the others.

How to create a propery solution?
-> We need create a synchronized view of the ArrayList as below code:

List intList = Collections.synchronizedList(new ArrayList<>());

-> Then blocking the implementation of function void adding(List intList) by using synchronized keyword to make sure that no having more than 1 thread doing the modification on the ArrayList instance at a specified time.

– Example:

-> Output:

Conclusion

Thanks for reading, We had learned:
– What is Java ArrayList?
– And how to use Java ArrayList with examples?

  • How to Add an Element to Java ArrayList
  • How to Add a Collection to Java ArrayList
  • How to Iterate Through ArrayList in Java
  • How to Get/Set Elements in Java ArrayList
  • How to Remove Elements in Java ArrayList
  • How to Search an Element in Java ArrayList
  • How to Get a View from Java ArrayList
  • How to create Java ArrayList of Custom User Defined Objects
  • How to Sort ArrayList in Java with Integer, String and User Defined Objects types
  • How to Synchronize Java ArrayList

Happy Learning! See you later!

By grokonez | May 19, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*