ArrayList in java

Java ArrayList class is a resizable array, which is part of the collection framework. It supports a dynamic array that can grow as needed. Java arrays have a fixed size. Once we create an array. Afterward, we can not be able to add or remove an element. But an ArrayList can grow in size when needed.
Internally, Java ArrayList also uses arrays to store data. When we need to grow, create a new array, and the elements, copied from the old array to the new array.

Constructors in the Java ArrayList:

To create a Java ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors, which allows the possible creation of the array list.
Following is the list of the constructors provided by the ArrayList class.

Constructor Description
ArrayList()It is used to build an empty array list
ArrayList(Collection c)This constructor builds an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)It is used to build an array list that has the specified initial capacity.

For example:

Create an arrayList object called animal that will store strings:

Import java.util.ArrayList;  // import the ArrayList class
ArrayList<String> animal = new ArrayList<string>();  //Create an                      ArayList object

Adding elements:

We can add elements to an ArrayList using the add() methods. So that appends one or more elements at the end of the list.

For example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Pig");
      System.out.printIn(animals);
  }  
}

Output

[Dog, cat, pig]

Access an element

To access an element in the arrayList, So that we use get() method and refer to the index number of an element which we want to access.

For example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Pig");
      System.out.printIn(animals.get(2));
  }  
}

As a Result

Pig

change An elemets.

We also can modify an element. For this, we use set() method and refer to the index number that we want to modify.

for example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("pig");
        animals.set(1, "Panda")
      System.out.printIn(animals);
  }  
}

As a Result:

[Panda, Cat, Pig]

Remove an element:

To remove an element, use the remove() method and also refer to the index number.

For example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("pig");
        animals.remove(1);
      System.out.printIn(animals);
  }  
}

As a Result:

[Dog,pig]

If we want to remove all the elements from arrayList , use clear() method

For example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("pig");
        animals.clear();
      System.out.printIn(animals);
  }  
}

As a result:

[]

Sort an element

Collections.sort () is another useful method to sort an ArrayList.

for example:

import java.util.ArrayList;

public class Main{
  public static void main(String[] args){
     ArrayList<String> animals = new ArrayList,<string>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("pig");
        Collections.sort(animals);     //Sort animals
          for  (String i : animals ){
      System.out.printIn(i);
    }
  }  
}

As a Result:

Dog
Cat
Pig

Methods of ArrayList:

Here are some important methods of array list as follow:

MethodDescription
void add(int index, E element)This method, used to insert the specified element at the specified position in a list.
boolean add(E e) Used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c)Boolean addAll() method, used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(int index, Collection<? extends E> c)Used to append all the elements in the specified collection, starting at the specified position of the list.
void clear()Used to remove all of the elements from this list.
void ensureCapacity(int requiredCapacity)It used to enhance the capacity of an ArrayList instance.
E get(int index)This method, used to fetch the element from the particular position of the list.
boolean isEmpty()It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
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 containing all of the elements in this list in the correct order.
Object clone()It is used to return a shallow copy of an ArrayList.
boolean contains(Object o)It returns true if the list contains the specified element
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.

More methods

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 retain all the elements in the list that are present in the specified collection.
E set(int index, E element)It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of specified comparator.
Spliterator<E> spliterator()It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements lies within the given range.
int size()It is used to return the number of elements present in the list.
void trimToSize()It is used to trim the capacity of this ArrayList instance to be the list’s current size.

Recommended Post:

Convert java object into a JSON

Difference between the Java and JavaScript

What is JavaScript?

Compilation and Execution of a java program

Reference:

w3school.com

javatpoint.com

Leave a Reply

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