ArrayList get(int index)
method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
This method throws IndexOutOfBoundsException if the index is less than zero or greater than the size of the list (index<0 OR index>= size of the list).
Example
In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com; import java.util.ArrayList; public class GetMethodExample { public static void main(String[] args) { ArrayList<String> al = new ArrayList<String>(); al.add("pen"); al.add("pencil"); al.add("ink"); al.add("notebook"); al.add("book"); al.add("books"); al.add("paper"); al.add("white board"); System.out.println("First element of the ArrayList: "+al.get(0)); System.out.println("Third element of the ArrayList: "+al.get(2)); System.out.println("Sixth element of the ArrayList: "+al.get(5)); System.out.println("Fourth element of the ArrayList: "+al.get(3)); } }
Output:
First element of the ArrayList: pen Third element of the ArrayList: ink Sixth element of the ArrayList: books Fourth element of the ArrayList: notebook
Reference:
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#get(int)
Rahul says
please explain the algorithm used when get(int index) is called. about RandomAccess