Java.util.ArrayList.get() Method

Published by user on

The java.util.ArrayList.get(int index) method returns the element at the specified index or position.

Syntax:

Let’s look at the syntax of ArrayList.get(int index).

public E get(int index)

Parameter:

The index is the position of the element to be returned.
E – The actual element to return.

Exception:

IndexOutOfBoundsException – If the index is out of range i.e (index < 0 || index >= size()). You cannot pass a negative argument to this method.

Example 1:

Program to demonstrate the use of java.util.ArrayList.get(int index)

import java.util.ArrayList;
import java.util.List;

// program to demonstrate the use
// of ArrayList get method
public class ArrayListDemo {

	public static void main(String[] args) {
		// create the arraylist
		List<Integer> arrList = new ArrayList<>();
		// add the elements
		arrList.add(10);
		arrList.add(20);
		arrList.add(55);
		arrList.add(93);
		arrList.add(70);
		// print the elements
		System.out.println("Elements are:");
		for (Integer i : arrList) {
			System.out.println("Value = " + i);
		}

		// get the element at index 2
		System.out.println("Element at index (2) = " + arrList.get(2));
	}
}

Output:

Elements are:
Elements are:
Value = 10
Value = 20
Value = 55
Value = 93
Value = 70
Element at index (2) = 55

Example 2:

get() throws IndexOutOfBoundsException if the index is out of range. Let’s have a look at the example.

import java.util.ArrayList;
import java.util.List;

// Program to demonstrate
// that get throws IndexOutOfBoundsException
// if the index is out of range
public class ArrayListDemo {

	public static void main(String[] args) {
		List<Integer> arrList = new ArrayList<>();
		arrList.add(10);
		arrList.add(20);
		arrList.add(30);
		arrList.add(40);
		arrList.add(50);

		System.out.println("Elements in the list:");
		for (Integer i : arrList) {
			System.out.println("Value = " + i);
		}

		// get the value of element at 7the
		// position which is out
		// of range
		System.out.println("Element at index 7 : " + arrList.get(7));
	}
}

Output:

Elements in the list:
Value = 10
Value = 20
Value = 30
Value = 40
Value = 50
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 5
	at java.util.ArrayList.rangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at ArrayListDemo.main(ArrayListDemo.java:25)
Categories: Java