Collections

Java ArrayList Get Example

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

How to get element from ArrayList in Java?

Java ArrayList class provides get method which 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, 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 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 object of Object class and you will have to cast it down to the appropriate type before you can use any methods of the 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. Explicit cast will be required to cast the element to the appropriate type as given below.

References:
1. ArrayList Javadoc

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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