Java ArrayList Get Example

Java ArrayList Get example shows how to get an element from ArrayList in Java. The example also shows how to get element with and without cast.

Java ArrayList is a part of the Java Collection framework.

How to get element from ArrayList in Java?

Java ArrayList get method returns the element at the specified index of the ArrayList.

This method returns the element at the specified index.

Example

Output

As you can see from the output, the ArrayList index starts from 0. So the first element of the ArrayList is located at index 0. The last element of the ArrayList is located at index (total size of the ArrayList – 1) index so in the above example at index 2.

If you try to access index which is out of the range (i.e. index < 0 or index >= ArrayList size), get method throws IndexOutOfBoundsException exception.

Output

You can use for loop or enhanced for loop to get all the elements and print ArrayList elements one by one as given below.

Output

Make sure to specify type when you declare an ArrayList. If ArrayList is declared without type, the get method returns an object of the Object class and you will have to cast it down to the appropriate type before you can use any methods of that class.

You will get “The method toLowerCase() is undefined for the type Object” compilation error. That is because since we have not specified any type while declaring the ArrayList, the get method returns object of Object class. The explicit cast will be required to cast the element to the appropriate type as given below.

This example is a part of the Java ArrayList tutorial with examples.

References:
1. ArrayList Javadoc

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *