An element can be get from the ArrayList in Java by using the ArrayList.get() method . This method returns the element at the specified position in this list.
Syntax :
public E get(int index) {
}
This method returns the element at the specified position in this list.
Parameters:
index – index of the element to return
Returns Value: It return the element at the specified position in this list
Exception – It throws following exception
IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())
import java.util.ArrayList;
public class GetElement {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
// print arraylist
System.out.println("arrayList is = " + arr);
System.out.println("Element At Index 2 ="+arr.get(2));
}
}
Output:
arrayList is = [c, php, html, java]
Element At Index 2 =html