Home core java Java ArrayList complete guide with Examples

Java ArrayList complete guide with Examples

In this article we will see what is Java ArrayList, it’s features, how do we create ArrayList in java and most commonly methods in ArrayList with simple examples.

1. What is Java ArrayList

The ArrayList in java is Resizable-array implementation of the List  interface for storing group of elements, which can be found in the java.util package.

1.1. Class hierarchy of Java ArrayList

ArrayList inherits AbstractList class and implements List interface, following image illustrates the class hierarchy of the ArrayList class.

ArrayList Java

2. Java ArrayList features

  1. ArrayList in java allows duplicate values to store.
  2. ArrayListallows null values to store.
  3. ArrayList preserves insertion order.
  4. The underlying data structure is Resizable-array (or) grow-able array.
  5. Methods are not Synchronized in ArrayList.

3. Creating ArrayList in Java :

ArrayList provides following constructors to create ArrayList objects.

  1.  ArrayList() ArrayList() :  is used to build an empty ArrayList object.
  2.  ArrayList(Collection c) : is used to build an ArrayList initialized with the elements from any other Collection c. This is useful to convert other List implementations to the ArrayList.
  3.  ArrayList(int capacity) : is used to build an ArrayList with initial capacity being specified
//Default constructor, create an empty ArrayList
ArrayList<Integer> list1 = new ArrayList<Integer>();

3.1. A basic ArrayList example

- Advertisement -
       //Default constructor, create an empty ArrayList
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		
		//add(Object o) -> adding elements
		list1.add(1);
		list1.add(5);
		list1.add(2);
		list1.add(3);
		list1.add(9);
		
		//print list1
		System.out.println("I am list1 : "+list1 +"\n");

Output :

I am list1 : [1, 5, 2, 3, 9]

4. Java ArrayList most commonly use methods and examples

Following are the ArrayList examples of most commonly used methods of ArrayList.

5.1. Add elements ArrayList example

  1. boolean add(Object o): is used to append a specified element to the end of a list.
  2. void add(int index, Object element): is used to insert a specific element at a specific position index in a list.
  3. boolean addAll(int index, Collection C): is used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
  4. boolean addAll(Collection C):  is used to append all the elements from a specific collection to the end of the mentioned list, in such a order that the values are returned by the specified collection’s iterator.
public class ArrayListAddDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		list1.add(1);
		list1.add(5);
		list1.add(3);
		
		//print list1
		System.out.println("List1 : "+list1 +"\n");
		System.out.println("Can add duplicate 3 to arrayList? : "+list1.add(3));
		System.out.println("List1 : "+list1+"\n");
		
		System.out.println("--- add 9 at index 1 ---"); 
		list1.add(1, 9);
		System.out.println("List1 : "+list1 +"\n");
		
		ArrayList<Integer> list2 = new ArrayList<Integer>();
		list2.add(15);
		list2.add(11);
		list2.add(20);
		System.out.println("List2 : "+list2+"\n"); 
		
		System.out.println("--- add all list1 items to list2 ---");
		list2.addAll(list1);
		System.out.println("List2 : "+list2+"\n");
		
		System.out.println("--- remove all list1 items to list2 ---");
		list2.removeAll(list1);
		System.out.println("List2 : "+list2+"\n");
		
		
		System.out.println("--- add all list1 items to list2 at index 1 ---");
		list2.addAll(1, list1);
		System.out.println("List2 : "+list2);
	}
}

Output results :

List1 : [1, 5, 3]

Can add duplicate 3 to arrayList? : true
List1 : [1, 5, 3, 3]

--- add 9 at index 1 ---
List1 : [1, 9, 5, 3, 3]

List2 : [15, 11, 20]

--- add all list1 items to list2 ---
List2 : [15, 11, 20, 1, 9, 5, 3, 3]

--- remove all list1 items to list2 ---
List2 : [15, 11, 20]

--- add all list1 items to list2 at index 1 ---
List2 : [15, 1, 9, 5, 3, 3, 11, 20]

5.2. Get elements from ArrayList example

  1. get​(int index): returns the element at the specified position in this list.
  2. int indexOf(Object O): is returns the index of the first occurrence of a specific element, or return -1 in case the element is not in the list.
  3. int lastIndexOf(Object O): returns the index of the last occurrence of a specific element, or return -1 in case the element is not in the list.
public class GetValuesAndIndexDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(5);
		list.add(3);
		list.add(1);
		list.add(3);
		
		//print list1
		System.out.println("List1 : "+list +"\n");
		System.out.println("element at index 0 => "+list.get(0));
		System.out.println("element at index 2 => "+list.get(2));
		System.out.println("index of 5 => "+list.indexOf(5));
		System.out.println("first index of 3 => "+list.indexOf(3));
		System.out.println("last index of 1 => "+list.lastIndexOf(1));
	}
}

Output :

List1 : [1, 5, 3, 1, 3]

element at index 0 => 1
element at index 2 => 3
index of 5 => 1
first index of 3 => 2
last index of 1 => 3

5.3. Set or update elements by index in ArrayList example

  1. set​(int index, E element): replaces the element at the specified position in this list with the specified element.
public class UpdateListItemDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(5);
		list.add(2);
		list.add(9);
		list.add(8);
		
		System.out.println("List => "+list+"\n");
		
		System.out.println("Update value 3 at index 2");
		list.set(2, 3);
		
		System.out.println("List => "+list);
	}
}

Output :

List => [1, 5, 2, 9, 8]

Update value 3 at index 2
List => [1, 5, 3, 9, 8]

5.4. Verify ArrayList contains value and get size example

  1. contains​(Object o): returns true if this list contains the specified element otherwise false.
  2. contains​All(Collection c): returns true if this list contains the specified list of elements otherwise false.
  3. isEmpty​(): returns true if this list contains no elements.
  4. size​(): Returns the number of elements in this list.
public class VerifyArrayListContainsAndSizeDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		list1.add(1);
		list1.add(5);
		list1.add(2);
		list1.add(9);
		list1.add(8);
		
		System.out.println("List1 : "+ list1);
		
		System.out.println("List1 contains 8? => "+list1.contains(8));
		System.out.println("List1 size => "+list1.size()+"\n");
		
		ArrayList<Integer> list2 = new ArrayList<Integer>();
		list2.add(1);
		list2.add(5);
		System.out.println("List2 : "+list2);
		
		ArrayList<Integer> list3 = new ArrayList<Integer>();
		list3.add(1);
		list3.add(11);
		
		System.out.println("List1 contains all of list 2 elements? => "+list1.containsAll(list2));
		System.out.println("List1 contains all of list 3 elements? => "+list1.containsAll(list3) +"\n");
		System.out.println("List1 is Empty ? => "+list1.isEmpty() +"\n");
	}
}

Output :

List1 : [1, 5, 2, 9, 8]
List1 contains 8? => true
List1 size => 5

List2 : [1, 5]
List1 contains all of list 2 elements? => true
List1 contains all of list 3 elements? => false

List1 is Empty ? => false

5.4. Remove elements from Java ArrayList example

  1. void clear():  is used to remove all the elements from any list.
  2. removeIf​(Predicate<? super E> filter): removes all of the elements of this collection that satisfy the given predicate.
  3. remove​(int index): removes the element at the specified position in this list.
  4. remove​(Object o): removes the first occurrence of the specified element from this list, if it is present.
  5. removeAll​(Collection<?> c): removes from this list all of its elements that are contained in the specified collection.
public class RemoveArrayListItemsDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		list1.add(1);
		list1.add(5);
		list1.add(2);
		list1.add(9);
		list1.add(5);
		list1.add(8);
		list1.add(11);
		list1.add(2);
		list1.add(3);
		
		System.out.println("List1 => "+list1);
		System.out.println("Remove element at index 0 => "+list1.remove(0));
		System.out.println("List1 => "+list1);
		System.out.println("Remove element 5 => "+list1.remove(Integer.valueOf(5)));
		System.out.println("List1 => "+list1);
		System.out.println("Remove if list has element 2 ?=> "+list1.removeIf(i -> i == 2));
		System.out.println("List1 => "+list1+"\n");
		
		ArrayList<Integer> list2 = new ArrayList<Integer>();
		list2.add(9);
		list2.add(5);
		System.out.println("List2 : "+list2);
		
		System.out.println("Remove all list2 elements from list1?=> "+list1.removeAll(list2));
		System.out.println("List1 => "+list1);
		
		list1.clear(); // empties list
		System.out.println("List1 => "+list1);
	}
}

Output :

List1 => [1, 5, 2, 9, 5, 8, 11, 2, 3]
Remove element at index 0 => 1
List1 => [5, 2, 9, 5, 8, 11, 2, 3]
Remove element 5 => true
List1 => [2, 9, 5, 8, 11, 2, 3]
Remove if list has element 2 ?=> true
List1 => [9, 5, 8, 11, 3]

List2 : [9, 5]
Remove all list2 elements from list1?=> true
List1 => [8, 11, 3]
List1 => []

5.5. Iterate Example

  1. forEach​(Consumer<? super E> action): performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
  2. listIterator​(): returns a list iterator over the elements in this list (in proper sequence).
  3. spliterator​(): creates a late-binding and fail-fast Spliterator over the elements in this list.
public class IterateArrayListItemDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(5);
		list.add(2);
		list.add(9);
		
		System.out.println("List => "+list);
		
		System.out.println("\n---- Enhanced for loop ----");
		for(Integer i : list)
			System.out.print("=>"+i);
		
		System.out.println("\n\n---- loop via iterator ----");
		Iterator<Integer> iterator = list.iterator();
		while (iterator.hasNext())
			System.out.print("=>"+iterator.next());
		
		System.out.println("\n\n---- loop via list iterator ----");
		ListIterator<Integer> listIterator = list.listIterator();
		while (listIterator.hasNext()) 
			System.out.print("=>"+listIterator.next());
				
			
		System.out.println("\n\n---- loop via spliterator ----");
		list.spliterator().forEachRemaining(i -> System.out.print("=>"+i));
		
		System.out.println("\n\n---- loop via forEach ----");
		list.forEach(i -> System.out.print("=>"+i));
		
		System.out.println("\n\n---- loop via stream ----");
		list.stream().forEach(i -> System.out.print("=>"+i));
	}
}

Output :

List => [1, 5, 2, 9]

---- Enhanced for loop ----
=>1=>5=>2=>9

---- loop via iterator ----
=>1=>5=>2=>9

---- loop via list iterator ----
=>1=>5=>2=>9

---- loop via spliterator ----
=>1=>5=>2=>9

---- loop via forEach ----
=>1=>5=>2=>9

---- loop via stream ----
=>1=>5=>2=>9

5.6. Filter Example

We can apply Stream filter to java ArrayList, following is examples shows you how to apply filter to arraylist.

public class FilterArrayListItemDemo {

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(5);
		list.add(2);
		list.add(9);
		
		System.out.println("List => "+list);
		
		System.out.println("--- Filter odd numbers using stream ---");
		list.stream()
		    .filter(i-> i%2 != 0)
		    .forEach(System.out::println);
	}
}

Output :

List => [1, 5, 2, 9]
--- Filter odd numbers using stream ---
1
5
9

References

  1. ArrayList document

- Advertisement -
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles