ArrayList in Java

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let’s create an ArrayList object named elements which stores string elements:

import java.util.ArrayList;    // Importing the ArrayList class from the java.util package

// Creating an ArrayList to store String elements
ArrayList<String> elements = new ArrayList<String>();

Java ArrayList is a part of the Java collections framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. The main advantage of ArrayList in Java is, that if we declare an array then we need to mention the size, but in ArrayList, it is not needed to mention the size of ArrayList. If you want to mention the size then you can do it.

What is ArrayList in Java?

ArrayList is a Java class implemented using the List interface. Java ArrayList, as the name suggests, provides the functionality of a dynamic array where the size is not fixed as an array. Also, as a part of the Collections framework, it has many features not available with arrays.

ArrayList Java

Illustration: 

Let us check on the ArrayList with the Integer Object type Stored in it with a image.

ArrayList_Integer_Object

Java ArrayList Example

Example 1: The following implementation demonstrates how to create and use an ArrayList with a mention of its size.

Java
// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;

class ArrayListExample {
    public static void main(String[] args)
    {
        // Size of the
        // ArrayList
        int n = 5;

        // Declaring the ArrayList with
        // initial size n
        ArrayList<Integer> arr1 = new ArrayList<Integer>(n);

        // Declaring the ArrayList
        ArrayList<Integer> arr2 = new ArrayList<Integer>();

        // Printing the ArrayList
        System.out.println("Array 1:" + arr1);
        System.out.println("Array 2:" + arr2);

        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= n; i++) {
            arr1.add(i);
            arr2.add(i);
        }

        // Printing the ArrayList
        System.out.println("Array 1:" + arr1);
        System.out.println("Array 2:" + arr2);
    }
}

Output
Array 1:[]
Array 2:[]
Array 1:[1, 2, 3, 4, 5]
Array 2:[1, 2, 3, 4, 5]

Explanation of the above Program:

ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:

  • Creates a bigger-sized memory on heap memory (for example memory of double size).
  • Copies the current memory elements to the new memory.
  • The new item is added now as there is bigger memory available now.
  • Delete the old memory.

Important Features of ArrayList in Java

  • ArrayList inherits AbstractList class and implements the List interface.
  • ArrayList is initialized by size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
  • ArrayList in Java can be seen as a vector in C++.
  • ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Let’s understand the Java ArrayList in depth. Look at the below image:

List Classes Interface

In the above illustration, AbstractList, CopyOnWriteArrayList, and AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:

  1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
  2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
  3. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in ArrayList in Java

In order to Create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:

1. ArrayList()

This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:

ArrayList arr = new ArrayList(); 

2. ArrayList(Collection c)

This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as: 

ArrayList arr = new ArrayList(c);  

3. ArrayList(int capacity)

This constructor is used to build an array list with the initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);

Java ArrayList Methods

MethodDescription
add(int index, Object element)This method is used to insert a specific element at a specific position index in a list.
add(Object o)This method is used to append a specific element to the end of a list.
addAll(Collection C)This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.
addAll(int index, Collection C)Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
clear()This method is used to remove all the elements from any list.
clone()This method is used to return a shallow copy of an ArrayList in Java.
contains? (Object o)Returns true if this list contains the specified element.
ensureCapacity?(int minCapacity)Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
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.
get?(int index)Returns the element at the specified position in this list.
indexOf(Object O)The index the first occurrence of a specific element is either returned or -1 in case the element is not in the list.
isEmpty?()Returns true if this list contains no elements.
lastIndexOf(Object O)The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.
listIterator?()Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index)Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
remove?(int index)Removes the element at the specified position in this list.
remove? (Object o)Removes the first occurrence of the specified element from this list, if it is present.
removeAll?(Collection c)Removes from this list all of its elements that are contained in the specified collection.
removeIf?(Predicate filter)Removes all of the elements of this collection that satisfy the given predicate.
removeRange?(int fromIndex, int toIndex)Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll?(Collection<?> c)Retains only the elements in this list that are contained in the specified collection.
set?(int index, E element)Replaces the element at the specified position in this list with the specified element.
size?()Returns the number of elements in this list.
spliterator?()Creates a late-binding and fail-fast Spliterator over the elements in this list.
subList?(int fromIndex, int toIndex)Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
toArray()This method is used to return an array containing all of the elements in the list in the correct order.
toArray(Object[] O)It is also used to return an array containing all of the elements in this list in the correct order same as the previous method.
trimToSize()This method is used to trim the capacity of the instance of the ArrayList to the list’s current size.

Note: You can also create a generic ArrayList:

// Creating generic integer ArrayList
ArrayList<Integer> arrli = new ArrayList<Integer>();

 Some Key Points of ArrayList in Java

  1. ArrayList is Underlined data Structure Resizable Array or Growable Array.
  2. ArrayList Duplicates Are Allowed.
  3. Insertion Order is Preserved.
  4. Heterogeneous objects are allowed.
  5. Null insertion is possible.

Let’s see how to perform some basic operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.

  • Adding element to List/ Add element
  • Changing elements/ Set element
  • Removing elements/Delete element 
  • Iterating elements   
  • get elements
  • add elements in between two number
  • Sorting elements
  • ArrayList size

Operations performed in ArrayList

1. Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:  

  • add(Object): This method is used to add an element at the end of the ArrayList.
  • add(int index, Object): This method is used to add an element at a specific index in the ArrayList.

Below is the implementation of the above approach:

Java
// Java Program to Add elements to An ArrayList

// Importing all utility classes
import java.util.*;

// Main class
class GFG {

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

        // Adding elements to ArrayList
        // Custom inputs
        al.add("Geeks");
        al.add("Geeks");

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

        // Printing all the elements in an ArrayList
        System.out.println(al);
    }
}

Output
[Geeks, For, Geeks]

2. Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. 

Below is the implementation of the above approach:

Java
// Java Program to Change elements in ArrayList

// Importing all utility classes
import java.util.*;

// main class
class GFG {

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

        // Adding elements to Arraylist
        // Custom input elements
        al.add("Geeks");
        al.add("Geeks");

        // Adding specifying the index to be added
        al.add(1, "Geeks");

        // Printing the Arraylist elements
        System.out.println("Initial ArrayList " + al);

        // Setting element at 1st index
        al.set(1, "For");

        //  Printing the updated Arraylist
        System.out.println("Updated ArrayList " + al);
    }
}

Output
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]

3. Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows: 

  • remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed.
  • remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.

Example:

Java
// Java program to Remove Elements in ArrayList

// Importing all utility classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of arraylist class
        ArrayList<String> al = new ArrayList<>();

        // Adding elements to ArrayList
        // Custom addition
        al.add("Geeks");
        al.add("Geeks");
        // Adding element at specific index
        al.add(1, "For");

        // Printing all elements of ArrayList
        System.out.println("Initial ArrayList " + al);

        // Removing element from above ArrayList
        al.remove(1);

        // Printing the updated Arraylist elements
        System.out.println("After the Index Removal " + al);

        // Removing this word element in ArrayList
        al.remove("Geeks");

        // Now printing updated ArrayList
        System.out.println("After the Object Removal "
                           + al);
    }
}

Output
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]

4. Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop

Example

Java
// Java program to Iterate the elements
// in an ArrayList

// Importing all utility classes
import java.util.*;

// Main class
class GFG {

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

        // Adding elements to ArrayList
        //  using standard add() method
        al.add("Geeks");
        al.add("Geeks");
        al.add(1, "For");

        // Using the Get method and the
        // for loop
        for (int i = 0; i < al.size(); i++) {

            System.out.print(al.get(i) + " ");
        }

        System.out.println();

        // Using the for each loop
        for (String str : al)
            System.out.print(str + " ");
    }
}

Output
Geeks For Geeks 
Geeks For Geeks 

5. Get Elements

Java
// Java program to get the elemens in ArrayList
import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
       ArrayList<Integer> list = new ArrayList();
     // add the number 
     list.add(9);
     list.add(5);
     list.add(6);
     System.out.println(list);
     // get method
     Integer n= list.get(1);
     System.out.println("at indext 1 number is:"+n);
    }
}

Output
[9, 5, 6]
at indext 1 number is:5

6. Add Elements Between Two Numbers

Java
// Java program to add the elements 
// between two numbers in ArrayList
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(4);
        System.out.println(list);
        // insert missing element 3
        list.add(2, 3);
        System.out.println(list);
    }
}

Output
[1, 2, 4]
[1, 2, 3, 4]

7. ArrayList Sort

Java
// Java Program for ArrayList Sorting
import java.io.*;
import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList();
        list.add(2);
        list.add(4);
        list.add(3);
        list.add(1);
        System.out.println("Before sorting list:");
        System.out.println(list);
        Collections.sort(list);
        System.out.println("after sorting list:");
        System.out.println(list);
    }
}

Output
Before sorting list:
[2, 4, 3, 1]
after sorting list:
[1, 2, 3, 4]

8. Size of Elements

Java
// Java program to find the size 
// of elements of an ArrayList
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList();

        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        int b = list.size();
        System.out.println("The size is :" + b);
    }
}

Output
The size is :4

Complexity of Java ArrayList

Operation

Time Complexity

Space Complexity

Inserting Element in ArrayList

O(1)

O(N)

Removing Element from ArrayList

O(N)

O(1)

Traversing Elements in ArrayList

O(N)

O(N)

Replacing Elements in ArrayList

O(1)

O(1)

ArrayList in Java is a class in the Java Collections framework that implements the List interface. Here are the advantages and disadvantages of using ArrayList in Java.

Advantages of Java ArrayList

  • Dynamic size: ArrayList can dynamically grow and shrink in size, making it easy to add or remove elements as needed.
  • Easy to use: ArrayList is simple to use, making it a popular choice for many Java developers.
  • Fast access: ArrayList provides fast access to elements, as it is implemented as an array under the hood.
  • Ordered collection: ArrayList preserves the order of elements, allowing you to access elements in the order they were added.
  • Supports null values: ArrayList can store null values, making it useful in cases where the absence of a value needs to be represented.

Disadvantages of Java ArrayList

  • Slower than arrays: ArrayList is slower than arrays for certain operations, such as inserting elements in the middle of the list.
  • Increased memory usage: ArrayList requires more memory than arrays, as it needs to maintain its dynamic size and handle resizing.
  • Not thread-safe: ArrayList is not thread-safe, meaning that multiple threads may access and modify the list concurrently, leading to potential race conditions and data corruption.
  • Performance degradation: ArrayList’s performance may degrade as the number of elements in the list increases, especially for operations such as searching for elements or inserting elements in the middle of the list.

Conclusion

Points to be remembered from this article are mentioned below:

  • ArrayList is the part of Collections framework. It inherits the AbstractList class and implements the List interface.
  • ArrayList is the implementation of a dynamic array.
  • ArrayList can be initialized used using different constructor types like without parameters, passing collection as a parameter, and passing integer as a parameter.
  • Operations can be performed in ArrayList as follows Adding, removing, iterating, and sorting.

FAQs of ArrayList

What is an ArrayList in Java?

An ArrayList is a resizable array that is part of the Java Collections Framework. It can dynamically grow and shrink as elements are added or removed.

How is ArrayList different from an Array in Java?

An ArrayList can resize dynamically, while a traditional array has a fixed size. ArrayList also provides many useful methods like add(), remove(), and size().

How to Create an ArrayList in Java?

ArrayList<String> list = new ArrayList<>();

Can ArrayList hold primitive types like int or char?

No, ArrayList can only hold objects. You must use wrapper classes like Integer or Character.

How to Add elements to an ArrayList?

We can add elements using the add() method:

list.add(“Hello”);

How to Access elements in an ArrayList?

Elements can be accessed using the get() method:

String element = list.get(0);

How to Remove an element from an ArrayList?

Use the remove() method to remove elements by index:

list.remove(0);

Is ArrayList Synchronized?

No, ArrayList is not synchronized. Use Collections.synchronizedList(new ArrayList<>()) for thread-safe operations.

Can we Store null elements in an ArrayList?

Yes, ArrayList can store null elements.

How to convert an ArrayList to an Array?

We can convert an ArrayList to an array using the toArray() method:

String[] array = list.toArray(new String[0]);

How is data stored in ArrayList?

ArrayList can store data till the ArrayList size is full, after that the size of ArrayList is doubled if we want to store any more elements.

Does ArrayList allow Duplicates?

Yes, ArrayList allows duplicate values to be stored.



Similar Reads

Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends 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. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.Arraylist.indexOf() in Java
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for. // Java code to demonstrate the working of // indexOf in ArrayList // for ArrayList functions import java.util.Arra
2 min read
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to
5 min read
Initialize an ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. ArrayList inherits AbstractList class and implements List interface.ArrayList is initialized by a size
3 min read
Arraylist removeRange() in Java with examples
The removeRange() method of ArrayList in Java is used to remove all elements within the specified range from an ArrayList object. It shifts any succeeding elements to the left. This call shortens the list by (toIndex-fromIndex) elements where toIndex is the ending index and fromIndex is the starting index within which all elements are to be removed
3 min read
ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax: get(index) Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list. Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size(
2 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
Arraylist.contains() in Java
In Java, ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Syntax of Java ArrayList contains() :public boolean contains(Object) object-element to be searched for Parameters: object- element whose presence in this list is to be tested Returns: It returns true if the specified element i
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
ArrayList clear() Method in Java with Examples
The clear() method of ArrayList in Java is used to remove all the elements from a list. The list will be empty after this call returns so whenever this operation has been performed all elements of the corresponding ArrayList will be deleted so it does it becomes an essential function for deleting elements in ArrayList from memory leading to optimiz
2 min read
ArrayList retainAll() method in Java
The retainAll() method of ArrayList is used to remove all the array list's elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method. Syntax: public boolean retainAll(Collection C) Parameters: The
4 min read
Array of ArrayList in Java
We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayL
2 min read
Reverse an ArrayList in Java using ListIterator
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an
6 min read
ArrayList spliterator() method in Java
The spliterator() method of ArrayList returns a Spliterator of the same elements as ArrayList but created Spliterator is late-binding and fail-fast. A late-binding Spliterator binds to the source of elements. It means that Arraylist at the point of the first traversal, first split, or the first query for estimated size, rather than at the time the
3 min read
ArrayList forEach() method in Java
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised. The operation is performed in the order of iteration if that order is specified by the method. Exceptio
2 min read
ArrayList removeIf() method in Java
The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method. Errors or runtime exceptions are thrown during iteration or by the predicate are pass to the caller. This method returns True, if we are able to remove some element. Java 8
3 min read
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList - An ArrayList is a part of the collect
6 min read
ArrayList iterator() method in Java with Examples
The iterator() method of ArrayList class in Java Collection Framework is used to get an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast. Syntax: Iterator iterator() Parameter: This method do not accept any parameter. Return Value: This method returns an iterator over the elements in this list in proper
2 min read
ArrayList ensureCapacity() method in Java with Examples
The ensureCapacity() method of java.util.ArrayList class increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. Syntax: public void ensureCapacity(int minCapacity) Parameters: This method takes the desired minimum capacity as a parameter
2 min read
ArrayList removeAll() method in Java with Examples
The removeAll() method of java.util.ArrayList class is used to remove from this list all of its elements that are contained in the specified collection. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this list. Returns Value: This method returns true if
3 min read
ArrayList listIterator() method in Java with Examples
listIterator() The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast. Syntax: public ListIterator listIterator() Return Value: This method returns a list iterator over the elements in this list (in proper sequence). Below
3 min read
ArrayList set() method in Java with Examples
The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the specified element. Syntax: public E set(int index, E element) Parameters: This method takes the following argument as a parameter. index- index of the element to replace element- element to be stored at the specified position
2 min read
ArrayList size() method in Java with Examples
The size() method of java.util.ArrayList class is used to get the number of elements in this list. Syntax: public int size() Returns Value: This method returns the number of elements in this list. Below are the examples to illustrate the size() method. Example 1: // Java program to demonstrate // size() method // for Integer value import java.util.
2 min read
ArrayList subList() method in Java with Examples
The subList() method of java.util.ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this li
3 min read
Find first and last element of ArrayList in java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to get the first and last element of the ArrayList in Java, Examples: Input: ArrayList = [1, 2, 3, 4] Output: First = 1, Last = 4 Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: First = 12, Last = 89 Approach: Get the ArrayList with elements.Get the first element of ArrayList w
2 min read
Remove all elements from the ArrayList in Java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to remove all elements of the ArrayList in Java. Examples: Input: ArrayList = [1, 2, 3, 4] Output: ArrayList = [] Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: ArrayList = [] Using clear() method: Syntax: collection_name.clear(); Code of clear() method: public void clear() {
2 min read
Remove repeated elements from ArrayList in Java
Prerequisite: ArrayList in Java Given an ArrayList, the task is to remove repeated elements of the ArrayList in Java. Examples: Input: ArrayList = [1, 2, 2, 3, 4, 4, 4] Output: [1, 2, 3, 4] Input: ArrayList = [12, 23, 23, 34, 45, 45, 45, 45, 57, 67, 89] Output: [12, 23, 34, 45, 57, 67, 89] Below are the various methods to remove repeated elements a
3 min read
How to sort an ArrayList in Descending Order in Java
Given an unsorted ArrayList, the task is to sort this ArrayList in descending order in Java. Examples: Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Output: Sorted ArrayList: [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal] Input: Unsorted ArrayList: [Geeks, For, ForGeeks] Output: Sorted ArrayList: [Gee
2 min read