0

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

2

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)
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1
if(index < ArrayList.size() && ArrayList.get(index) != null)
Michael Dz
  • 3,655
  • 8
  • 40
  • 74