Categories: Java

Java ArrayList in Collection Framework

The java.util package contains the collection foundation component ArrayList. In Java, it offers us dynamic arrays. Although it might be slower than conventional arrays, it can be useful in programs that require a lot of array manipulation. The java.util package contains this class.

Java ArrayList class Declaration:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable 
crucial things to keep in mind:
  • Duplicate elements are possible in Java’s ArrayList class.
  • The Java ArrayList class preserves the order of insertion.
  • The Java class for array lists is not synchronized.
  • Because the array operates on an index basis, Java ArrayList permits random access.
  • Because there needs to be a lot of shifting done if any element is removed from the array list, manipulation of an array list takes a bit longer than it does with a LinkedList in Java.
  • The primitive types, such as int, float, char, etc., cannot be organized into an array list. In such circumstances, the necessary wrapper class must be used.
Constructors of ArrayList:

1)ArrayList():The ArrayList() constructor is used to create an empty array list. The following code can be used to generate an empty ArrayList named ar:

ArrayList ar = new ArrayList(); 

2)ArrayList(Collection c): An array list is created using this constructor and its initial components are taken from the collection x. If we were to create an array list called ar that contained all the entries in the collection x, we could do so by:

ArrayList arr = new ArrayList(x); 

3)ArrayList(int capacity): This constructor is used to create an array list with a specified beginning capacity. If we were to build an ArrayList with N as the starting size, we could do it as follows:

ArrayList arr = new ArrayList(N);  
Methods of ArrayList:
MethodDescription
void add(int index, E element)It is used to insert the provided element into a list at the designated location.
boolean add(E e)A list’s provided element is added at the end using this method.
boolean addAll(Collection<? extends E> c)It is used to add each element from the provided collection, in the order that the iterator for that collection returns them, to the end of this list.
boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear()It is used to eliminate every item from this list.
void ensureCapacity(int requiredCapacity)It is used to increase an ArrayList instance’s capacity.
E get(int index)It is used to retrieve the element from a certain spot in the list.
boolean isEmpty()If the list is empty, it returns true; otherwise, it returns false.
int lastIndexOf(Object o)It is used to return the index of the last instance of the supplied element in this list, or -1 if the element isn’t present in the list.
Object[] toArray()It is used to return an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a)It is used to return an array with every item in this list organized properly.
Object clone()It is used to return a shallow copy of an ArrayList.
boolean contains(Object o)If the requested element is present in the list, it returns true.
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index)It is used to remove the element present at the specified position in the list.
boolean remove(Object o)It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c)It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> filter)It is used to remove all the elements from the list that satisfies the given predicate.
protected void removeRange(int fromIndex, int toIndex)It is used to remove all the elements lies within the given range.
void replaceAll(UnaryOperator<E> operator)It is used to replace all the elements from the list with the specified element.
void retainAll(Collection<?> c)It is used to keep all of the list’s elements that are part of the chosen collection.
E set(int index, E element)The specified element in the list that is present at the specified position is replaced using this.
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of the specified comparator.
Spliterator<E> spliterator()It is used to create a spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements that lie within the given range.
int size()The number of elements in the list is returned using this method.
void trimToSize()It is used to trim the capacity of this ArrayList instance to be the list’s current size.
Example: Adding Elements

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Creating an Array of string type
  ArrayList<String> ar = new ArrayList<>();

  // Adding elements to ArrayList
  // Custom inputs
  ar.add("Coding");
  ar.add("Coderz");

  // Here we are mentioning the index
  // at which it is to be added
  ar.add(1, "at");

  // Printing all the elements in an ArrayList
  System.out.println(ar);
 }
}
Output:
[Coding, at, Coderz]
Example: Changing Elements

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Creating an Array of string type
  ArrayList<String> ar = new ArrayList<>();

  // Adding elements to ArrayList
  // Custom inputs
  ar.add("Coding");
  ar.add("Coderz");

  // Here we are mentioning the index
  // at which it is to be added
  ar.add(1, "at");

  // Printing all the elements in an ArrayList
  System.out.println("Initial ArrayList "+ar);
    // Setting element at 1st index
        ar.set(1, "For");
  
        //  Printing the updated Arraylist
        System.out.println("Updated ArrayList " + ar);
 }
}
Output:
Initial ArrayList [Coding, at, Coderz]
Updated ArrayList [Coding, For, Coderz]
Example: Iterating the ArrayList

import java.util.*;

// Main class
class Coderz {

 // Main driver method
 public static void main(String args[])
 {
  // Creating an Array of string type
  ArrayList<String> ar = new ArrayList<>();

  // Adding elements to ArrayList
  // Custom inputs
  ar.add("Coding");
  ar.add("Coderz");

  // Here we are mentioning the index
  // at which it is to be added
  ar.add(1, "at");
  for (int i = 0; i < ar.size(); i++) {
  
            System.out.print(ar.get(i) + " ");
        }
  
        System.out.println();
 }
}
Output:
Coding at Coderz
Coding at Coderz 

Note: also read about the Java Iterator for Collection Access

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago