Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaArrayList get(index) Method in Java with Examples

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()) 

Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get(index) is always a constant time O(1) operation.

Example:

Java




// Java Program to Demonstrate the working of
// get() method in ArrayList
  
// Importing ArrayList class
import java.util.ArrayList;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an Empty Integer ArrayList
        ArrayList<Integer> arr = new ArrayList<Integer>(4);
  
        // Using add() to initialize values
        // [10, 20, 30, 40]
        arr.add(10);
        arr.add(20);
        arr.add(30);
        arr.add(40);
  
        // Printing elements of list
        System.out.println("List: " + arr);
  
        // Getting element at index 2
        int element = arr.get(2);
  
        // Displaying element at specified index
        // on console inside list
        System.out.println("the element at index 2 is "
                           + element);
    }
}


Output

List: [10, 20, 30, 40]
the element at index 2 is 30

Example 2: Program to demonstrate the error

Java




// Java Program to Demonstrate Error Generated
// while using get() method in ArrayList
  
// Importing ArrayList class
import java.util.ArrayList;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an Empty Integer ArrayList
        ArrayList<Integer> arr = new ArrayList<Integer>(4);
  
        // Using add() method to insert elements
        // and adding custom values
        arr.add(10);
        arr.add(20);
        arr.add(30);
        arr.add(40);
  
        // Getting element at index 2
        int element = arr.get(5);
  
        // Print all the elements of ArrayList
        System.out.println("the element at index 2 is "
                           + element);
    }
}


Output : 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at GFG.main(GFG.java:22)

Previous article
Next article
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments