简体   繁体   中英

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.

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
}

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.

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()) {
    ...
}

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.

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
}

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

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

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;
}

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'
    }
}

a simple way to do this:

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

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()

Scanner input = new Scanner(System.in);
    System.out.println("Enter the index to check");
    int i  = input.nextInt();
    if (i > tasksList.size() || i < 0 ){
        System.out.println("invalid input");
    }else {
            //your code
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM