138

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.

2

13 Answers 13

205

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
}
6
  • 12
    That should be "greater or equal to the size()" since it is a zero-based index.
    – McDowell
    Jan 25, 2010 at 11:18
  • 1
    Also worth mentioning that to make this atomic you should probably perform the size() check and corresponding conditional index based look-up whilst locking the list.
    – Adamski
    Jan 25, 2010 at 11:22
  • 6
    please note that i mark this answer at the correct is because the owner (Amarghosh) as answered my question in a comment to my question. HashTable will suite my needs much better.
    – ufk
    Jan 25, 2010 at 11:31
  • what if you are setting items in the arraylist with ID of the item? ex. mylist.set(1, item1); mylist.set(3, item3); //skipping 2 I guess HashMap is more suitable for that scenario?
    – yeahman
    Feb 27, 2016 at 6:55
  • this doesn't quite satisfy me .. if I want to do something in the list if the index is already there, but otherwise to prep it.. with a new list I'm going to start at index = 0 and my list.size() == 0 too. so the first time I check it will be true & I'll prep the list to do stuff. but the next time at that index, my index will still be index = 0 and now I am re-initializing that element in the list when I was supposed to be doing stuff. The 1st thought is to && a second condition like list.get(index) == null but that not working is why there are questions like this one May 10, 2016 at 19:10
87

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.

5
  • 3
    Thank you, needed this technique for unit testing whether array indexes exist.
    – Noumenon
    Sep 3, 2013 at 4:34
  • 20
    Remember to avoid using try/catch for this kind of work, it will slow down your program by 50% or maybe more.. error checking adds like a strap to your existing code to slow it down.. better to avoid it in critical areas. Checking for length in this case is the best thing you can do, since the index will always be less then the length,old index's will get shifted and become new index's if you remove them so that's why the rule checking for length always will work.
    – SSpoke
    Apr 9, 2014 at 7:47
  • 1
    @SSpoke ... While I agree, try/catch is far from 'a good' answer; it will address the problem when the list is sparse. I prefer the suggestion to use an array: Object[] ary; below or a hash.
    – will
    Nov 4, 2014 at 2:16
  • 2
    Using exceptions to for flow control, as this example shows, it is an anti-pattern softwareengineering.stackexchange.com/questions/189222/…
    – Tk421
    Jul 25, 2021 at 2:22
  • Accessing an out of bound element can be prevented with length check. Try to avoid exception handlers for situations which can be guarded. Exceptions are for exceptional behaviour, something which you couldn't have foreseen. Sir Martin Fowler goes in length for this one martinfowler.com/articles/replaceThrowWithNotification.html
    – iCantC
    Aug 16 at 3:33
14

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.

1
  • 6
    Not always, since he might want the ArrayList to grow over time, and that a array can't do.
    – Coyote21
    Apr 11, 2011 at 21:51
12

This is for Kotlin developers ending up here:

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

Other solutions:

// The rangeUntil operator (..<) is still exprimental in Kotlin 1.7.20
if (index in 0..<myList.size) {
  // index is valid
}
if (index in 0 until myList.size) {
  // index is valid
}
if (index in 0..myList.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
}
2
  • This is why I love Kotlin :D
    – F.Mysir
    Aug 7, 2022 at 16:28
  • Awesome solution! Kotlin ❤️
    – msal
    Sep 1, 2022 at 19:44
11

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()) {
    ...
}
2
  • 2
    How does this provide any value over the accepted Answer of several years ago? Jan 14, 2018 at 21:06
  • 4
    I guess in your view it does not provide any value, but I saw a comment of roberto tomás on the accepted answer, assuming he did not quite understood the accepted answer. check it out "with a new list I'm going to start at index = 0 and my list.size() == 0 too. so the first time I check it will be true" I decided to post a separate answer to help any future confusion.
    – AamirR
    Jan 14, 2018 at 21:22
6

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.

1
  • 3
    If array[8] does not exist, you will encounter ArrayIndexOutOfBoundException. May 15, 2019 at 19:14
6

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
1
3

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

1

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'
    }
}
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;
}
2
  • 1
    List don't have .length it has list.size() but it's no big deal I screw up like this all the time haha I rely on compiler to guide me on that one. You were probably thinking of primitive arrays
    – SSpoke
    Apr 9, 2014 at 7:43
  • 1
    Thanks for catching that. The containers cardinality can be easy to forget.
    – t3dodson
    Apr 10, 2014 at 22:01
1

a simple way to do this:

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

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

4
  • 1
    Calling ensureCapacity(int) won't increase the size of the List, only the capacity; i.e. "potential size" so out of bounds index look-ups would still fail.
    – Adamski
    Jan 25, 2010 at 11:19
  • Also, why call ensureCapacity(int) at all? It could be an incredibly expensive operation if for example the list's current size is 5 and you want to determine the value of item#: 100,000,000.
    – Adamski
    Jan 25, 2010 at 11:20
  • I meant that indices less than size() always exist, those which are >= size() don't and one can't use them (== call set()) until list becomes big enough. Calling ensureCapacity is not enough indeed, one needs to change the size by adding elements.
    – Dmitry
    Jan 25, 2010 at 12:19
  • Wrong explanation about what ensureCapacity(int) actually does. It does nothing with ArrayList size.
    – Mohsen
    Feb 7, 2012 at 17:14
0
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
        }
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 8, 2022 at 17:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.