How get method of ArrayList work internally in java

Sometime in the interview, you may encounter this question. Here we will see how get() method has been implemented. Let’s see an example where we will iterate ArrayList using get() method.

import java.util.ArrayList;
import java.util.List;
 
public class ArraListExample {
 
	public static void main(String[] args) {
 
		List<String> listObject = new ArrayList<>();
 
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
 
		for (int i = 0; i < listObject.size(); i++) {
			System.out.println(listObject.get(i));
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Let’s see how get() method is implemented.

 

  public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

 

Inside get() method, we have rangeCheck() and elementData() method. we will see one by one.

rangeCheck() implementation –

 private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

rangeCheck() make sure whatever index we are passing is not greater than size if it is, throws an exception. for example, if we have 5 elements in the list and we try to get 6 elements it will throw an Exception.

 

elementData() implementation –

 E elementData(int index) {
        return (E) elementData[index];
 }

It will return an element from the elementData array for given index. We have elementData array defined in the ArrayList class.

transient Object[] elementData;