Java ArrayList.get() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.get() method. Java.util.ArrayList.get() method returns the element at the specified position in this list.

syntax

Returns the element at the specified position in this list

E java.util.ArrayList.get(int index)

Parameter

index - index of the element to return

Return

Returns the element E at the specified position in this list

Exception

throws IndexOutOfBoundsException exception if you try to get element out of range (index < 0 || index >= size()). To avoid this exception always check check out of range condition.

Java ArrayList.get(int index) example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Get the element from specified index position. colors.get(1) returns Green value.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListSize {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        System.out.println("Element at 1 index:- " + colors.get(1));
    }
}

Output

Element at 1 index:- Green

IndexOutOfBoundsException

If you try to get the element out of range (colors.get(4)), program throws java.lang.IndexOutOfBoundsException exception.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
 at java.util.ArrayList.rangeCheck(ArrayList.java:653)
 at java.util.ArrayList.get(ArrayList.java:429)
 at com.technicalkeeda.app.ArrayListSize.main(ArrayListSize.java:13)


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0330 seconds.