ArrayList - how can I check if an index exists?

JavaArraylist

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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
}

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

Usually I just check if the index is less than the array size

if (index < list.size()) {
    ...
}

If you are also concerned of index being a negative value, use following

if (index >= 0 && index < list.size()) {
    ...
}

Solution 5 - Java

Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:

Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
   // not available
}
else {
   // do something
}

Best-Practice

If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.

Control flow using exception is bad practice.

Solution 6 - Java

Since Java 9 there is a standard way of checking if an index belongs to the array - Objects#checkIndex() :

List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException

Solution 7 - Java

This is for Kotlin developers ending up here:

if (index in myList.indices) {
  // index is valid
}

Other solutions:

if (index in 0..myArray.lastIndex) {
  // index is valid
}
if (index >= 0 && index <= myList.lastIndex) {
  // index is valid
}
// Note: elements of the list should be non-null
if (myList.getOrNull(index) != null) {
  // index is valid
}
// Note: elements of the list should be non-null
myList.getOrNull(index)?.let { element ->
  // index is valid; use the element
}

Solution 8 - Java

You can check the size of an ArrayList using the size() method. This will return the maximum index +1

Solution 9 - Java

You could check for the size of the array.

package sojava;
import java.util.ArrayList;

public class Main {
    public static Object get(ArrayList list, int index) {
        if (list.size() > index) { return list.get(index); }
        return null;
    }

    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(""); list.add(""); list.add("");        
        System.out.println(get(list, 4));
        // prints 'null'
    }
}

Solution 10 - Java

Quick and dirty test for whether an index exists or not. in your implementation replace list With your list you are testing.

public boolean hasIndex(int index){
	if(index < list.size())
		return true;
	return false;
}

or for 2Dimensional ArrayLists...

public boolean hasRow(int row){
	if(row < _matrix.size())
		return true;
	return false;
}

Solution 11 - Java

a simple way to do this:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

Solution 12 - Java

If your index is less than the size of your list then it does exist, possibly with null value. If index is bigger then you may call ensureCapacity() to be able to use that index.

If you want to check if a value at your index is null or not, call get()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionufkView Question on Stackoverflow
Solution 1 - JavaAmarghoshView Answer on Stackoverflow
Solution 2 - JavapliView Answer on Stackoverflow
Solution 3 - JavaPaul McKenzieView Answer on Stackoverflow
Solution 4 - JavaAamirRView Answer on Stackoverflow
Solution 5 - JavastackerView Answer on Stackoverflow
Solution 6 - JavaAnton BalaniucView Answer on Stackoverflow
Solution 7 - JavaMahozadView Answer on Stackoverflow
Solution 8 - JavajwoolardView Answer on Stackoverflow
Solution 9 - JavamikuView Answer on Stackoverflow
Solution 10 - Javat3dodsonView Answer on Stackoverflow
Solution 11 - JavaJosuéView Answer on Stackoverflow
Solution 12 - JavaDmitryView Answer on Stackoverflow