ArrayList.get(int): This method is available in java.util.ArrayList class of Java.
Syntax:
Integer java.util.ArrayList.get(int index)
This method takes one argument of type int as its parameter. This method returns the element at the specified position in this list.
Parameters: One parameter is required for this method.
index: index of the element to return.
Returns: the element at the specified position in this list.
Throws:
IndexOutOfBoundsException - if the index is out of range(index < 0 || index >= size())
Approach 1: When no exceptions
Java
import java.util.ArrayList;public class ArrayListget {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(3);System.out.println(arr.get(0));}}
Output:
1
Approach 2: IndexOutOfBoundsException
Java
import java.util.ArrayList;public class ArrayListget {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(3);System.out.println(arr.get(4));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427)
No comments:
Post a Comment