java: ArrayList - how can I check if an index exists?

The method arrayList.size() returns the number of items in the list - so if the index is greater than or equal to the size(), it doesn't exist.

if(index >= myList.size()){
  //index not exists
}else{
 // index exists
}

While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.

If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.

Using if ( list.get(index) == null ) will not work either, as get() throws an exception instead of returning null.

Try this:

try {
    list.get( index );
} catch ( IndexOutOfBoundsException e ) {
    list.add( index, new Object() );
}

Here a new entry is added if the index does not exist. You can alter it to do something different.


This is what you need ...

public boolean indexExists(final List list, final int index) {
    return index >= 0 && index < list.size();
}

Why not use an plain old array? Indexed access to a List is a code smell I think.

Tags:

Java

Arraylist