Search code examples
javaarraylistindexoutofboundsexception

I want to check if index of ArrayList is declared, without using get


I try to get an element from an Arraylist using an index, and check if it is empty or not.

I tried:

if(!ArrayList.get(index)) {
    // do something
}

And it gets Index out of Bounds exception.

Of course I can use try-catch, but I'd like to know if there is any other way of doing this without using try-catch?

I think I can do it more simply, but I can't. I tried to read the API documentation, but it seems like there is no such thing as what I want to do.


Solution

  • You could just check the list's size() (and of course, it must also be non-negative):

    if (index >= 0 && index < myList.size()) {
        // Do something with myList.get(index)
    }