javaarraylist

ArrayList - how can I check if an index exists?


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.


Solution

  • 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 < 0){
      //index does not exists
    }else{
     // index exists
    }