X
    Categories: Java Core

Java ArrayList Example

Java ArrayList class is a resizable array that implements the List interface. It permits all elements, including null and also implements all optional list operations. Most operations that can be run on ArrayList such as size, isEmpty, get, set, iterator and listIterator are all constant time. However, the add operation’s complexity is O(n) time. Compared to LinkedList, the constant factor is low.

Advantages of ArrayList

  • The ability to dynamically add or remove elements.
  • ArrayList uses an array as its underlying implementation which grants ArrayList class a faster access to elements.
  • Flexibility.
  • ArrayList is object-oriented so you can extend from it and add a functionality, if needed.
  • Adding custom behaviour to ArrayList is possible and even easy to achieve.

Limitations of ArrayList

  • Adding an element takes O(n) time.
  • ArrayList stores data sequentially in the memory so if the list is large, it will need significant contiguous blocks of memory.
  • The initial capacity of ArrayList is 10 and if we do not specify the capacity, we are going to have performance limitation. Everytime when ArrayList hits its own capacity, data will be copied from old to new space with 50% more capacity.



Simple illustration of ArrayList

ArrayList in Java

From the image above, we can see that currently there are 2 elements in the ArrayList and the maximum number of elements that can be added (the capacity) is 8 (or 6 more).

Constructors in ArrayList

  1. ArrayList() – Constructs an empty list with an initial capacity of ten.
  2. ArrayList(Collection<? extends E> c) – Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
  3. ArrayList(int initialCapacity) – Constructs an empty list with the specified initial capacity.

Methods in ArrayList class

  1. boolean add(E e): appends the specified element to the end of the list.
  2. void add(int index, E element): inserts the specified element at the specified position in the list.
  3. boolean addAll(Collection<?extends E> c): appends all of the elements in the specified collection to the end of the list, in the order that they are returned by the specified collection’s Iterator.
  4. boolean addAll(int index, Collection<? extends E> c): inserts all the elements within the collection into the list starting at the specified position.
  5. void clear(): removes all elements from the list.
  6. boolean contains(Object o): if the list contains the specified element, return true; otherwise return false.
  7. void ensureCapacity(int minCapacity): increases the capacity of the list if it is necessary to ensure that it can hold all the elements specified by the minimum capacity argument.
  8. void forEach(Consumer<? super E> action): performs the given action to every element it has been looped through.
  9. int indexOf(Object o): returns -1 if the list does not contain the element. If the element is present in the list however, it returns the index of the first occurrence of the specified element in this list.
  10. boolean isEmpty(): returns true if the list contains no elements.
  11. Iterator<E> iterator(): returns an iterator over the elements in the list in proper sequence.
  12. int lastIndexOf(Object o): returns the index of the last occurrence of specified element in the list or -1 if the element is not present in the list.
  13. boolean remove(Object o): removes the first occurrence of the specified from the list.
  14. boolean removeAll(Collection<?> c): removes from the list all of its elements that are contained in the specified collection
  15. boolean removeIf(Predicate<? super E> filter): removes all elements of this collection that satisfy the given predicate.
  16. protected void removeRange(int fromIndex, int toIndex): removes all elements in the list that are between fromIndex and toIndex. (fromIndex – inclusive, toIndex – exclusive)
  17. void replaceAll(UnaryOperator<E> operator): replaces each element of the list with the result of applying the operator to that element.
  18. boolean retainAll(Collection<?> c): returns only the elements in the list that are contained in the specified collection.
  19. int size(): returns the size of the list.
  20. void sort(Comparator<? super E> c): sorts the list according to the order specified by Comparator.
  21. Object[] toArray(): returns an array containing the elements that are contained in the list.

For documentation for all the methods, you can visit the Oracle official documentation page.

Adding elements in ArrayList using add()

import java.util.* ;

public class ArrayListEgTwo
{

  public static void main ( String[] args)
  {
    // Create an ArrayList that consists of Strings
    ArrayList<String> animals = new ArrayList<String>();

    // Capacity starts at 10, but size starts at 0
    System.out.println("initial size: " + animals.size());

    // Populating some of the arraylist
    animals.add("Elephant");
    animals.add("Tiger");
    animals.add("Lion");
    System.out.println("new size: " + animals.size());
}

Output:

size: 0
new size: 3

Removing elements in ArrayList using remove()

import java.util.* ;
public class RemoveExample
{
  public static void main ( String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();

    animals.add( "Elephant" );    
    animals.add( "Tiger" );
    animals.add( "Lion" );  

    names.remove(1);

    for ( int i=0; i < animals.size(); i++ )
      System.out.println( i + ": " + animals.elementAt(j) ); 

  }
}

Output:

0: Elephant
1: Lion

Checking if an ArrayList has elements using isEmpty()

import java.util.* ;

public class isEmptyExample
{
  public static void main ( String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();

    System.out.println( "Case 0:" + animals.isEmpty());
    
    animals.add("Tiger");    
    System.out.println( "Case 1:" + animals.isEmpty() );
    
    nobby.clear();    
    System.out.println( "Case 2:" + animals.isEmpty() );
  }
}

Output:

Case 0: true
Case 1: false
Case 2: true

Searching for an element in an ArrayList using indexOf(Object o)

import java.util.* ;
public class IndexOfExample
{
  public static void main (String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();

    animals.add("Elephant");     
    animals.add("Tiger");
    animals.add("Lion");   

    System.out.println("Index of 'Elephant': " + animals.indexOf("Elephant" )); 
    System.out.println("Index of 'Lion': " + animals.indexOf("Lion")); 
  }
}

Output:

Index of 'Elephant': 0
Index of 'Lion': 2

Iterating through elements in ArrayList using Iterator()

import java.util.* ;
public class IteratorExample
{
  public static void main ( String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();
    animals.add("Elephant");
    animals.add("Tiger");
    animals.add("Lion");

    // Initializing an iterator
    Iterator<String> iterator = animals.iterator();

    // Using the iterator to visit each element
    while(iterator.hasNext())
      System.out.println(iterator.next());

  }
}

Output:

Elephant
Tiger
Lion

Iterating through elements in ArrayList using Enhanced For Loop

import java.util.* ;
public class ForLoopExample
{
  public static void main ( String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();

    animals.add("Elephant");
    animals.add("Tiger");
    animals.add("Lion");

    for (String animal : animals) 
      System.out.println(animal);
  }
}

Output:

Elephant
Tiger
Lion

Getting the size of ArrayList using size()

import java.util.* ;
public class ForLoopExample
{
  public static void main ( String[] args)
  {
    ArrayList<String> animals = new ArrayList<String>();

    animals.add("Elephant");
    animals.add("Tiger");
    animals.add("Lion");

    System.out.println("Size of ArrayList: " + animals.size());
  }
}

Output:

Size of ArrayList: 3

 

0 0 votes
Article Rating
ym_coding:
Related Post