Skip to content

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

2 comments

  1. Hi
    Can you do example for an ArrayList that has many objects of atype, and you need to print/access one of them and them?
    Also, if you wanted just one variable in that object to print or take, from one or many of the objects.
    The array list is in another Class, and it is also private.
    Thanks again 🙂

    1. Hi Meepa,

      To print an object from the ArrayList, get the object using the index as shown in the example, and print it. Make sure that the Class implements the toString method, otherwise it will not print any useful details.

      I hope this answers your question. Good luck and thanks.

Leave a Reply

Your email address will not be published.