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

ufk picture ufk · Jan 25, 2010 · Viewed 231.9k times · Source

I'm using ArrayList<String> and I add data at specific indices, how can I check if a specific index exists?

Should I simply get() and check the value? Or should I wait for an exception? Is there another way?

Update

Thank you for your answers, but because I'm only adding stuff at specific indices, the length of the list will not show me which are available.

Answer

Amarghosh picture Amarghosh · Jan 25, 2010

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
}