Get Element from Arraylist

Arraylist get(int index) method is used for fetching an element from the list .  We need to specific the index while calling and it return value present at the specific element.

public Element get(int index)

This method throws IndexOutOfBoundException if the index is less than zero or greater than the size of the list (index <0 OR index >=size of the list)

import java.util.ArrayList;

public class Example {

public static void main(String[] args) {
ArrayList<String> arrlist = getArrayList();
}
public static ArrayList<String> getArrayList(){ ArrayList<String> arrlist = new ArrayList<String>(); //add method for String ArrayList arrlist.add("Item1"); arrlist.add("Item2"); arrlist.add("Item3"); arrlist.add("Item4"); arrlist.add("Item5"); System.out.println("ArrayList element Item1 of index 0 = "+ arrlist.get(0)); System.out.println("ArrayList element Item2 of index 1 = "+ arrlist.get(1)); System.out.println("ArrayList element Item3 of index 2 = "+ arrlist.get(2)); System.out.println("ArrayList element Item4 of index 3 = "+ arrlist.get(3)); return arrlist; }
}

//we saw it return as values to a list

ArrayList element Item1 of index 0 = Item1
ArrayList element Item2 of index 1 = Item2
ArrayList element Item3 of index 2 = Item3
ArrayList element Item4 of index 3 = Item4


EmoticonEmoticon