Questions tagged [indexoutofboundsexception]

An exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects. This is a language-independent tag.

An IndexOutOfBoundsException is an exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects.

IndexOutOfBoundsExceptions are generally caused by one of 2 things...

  1. Passing a negative pointer index
  2. Passing a pointer that is equal-to, or greater than the length of the container.

If we use the example of an array which is defined as being able to hold 4 objects...

Object[] myArray = new Object[4];

Arrays, and array-based containers, in most languages have zero-based references (See Wikipedia for a list of exceptions). This means that the first item in the array is myArray[0], not myArray[1]. For new programmers, this is often not obvious, and can result in them trying to reference objects from 1-4 rather than 0-3. This causes the programmer to receive an IndexOutOfBoundsException when trying to reference myArray[4].

A common way to make this mistake is to use a for loop as follows:

for (int i=0; i<=myArray.Length; i++)
    // do something with myArray[i];

This will fail with an IndexOutOfBoundsException because only elements [0] through [3] exist. myArray[myArray.Length] is myArray[4], which does not exist.

Similarly, trying to reference a negative index, such as myArray[-1] will fail, as it exists outside the bounds of the array. This would commonly occur when trying to obtain an index reference from another method, where the method is using a negative number to indicate a failure.

For example, assume the following code...

String myName = "Fred";
Object myObject = myArray[myName.getIndexOf("B")];

In this example, the getIndexOf("B") method will find the position of the letter B in the given String. However, when trying to use this method in the code above, the letter B is not found in the word Fred, therefore it returns -1 to indicate it was not found. If we then attempt to use that value as a reference to an item of an array, it will fail.

To help avoid these exceptions, it is usually good practice to perform a check before attempting to reference an item of a collection. For example...

int indexPointer = 2;
if (indexPointer >= 0 && indexPointer < myArray.length){
    // the index is within the bounds of the array
    Object myObject = myArray[indexPointer];
}

Canonical Question/Answers:

2854 questions
11
votes
3 answers

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 exception

I am getting the error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. public Collection getAdDistribution(byte srch, byte cont) throws IndexOutOfBoundsException { List mediums = new ArrayList<>(); …
Manju
  • 199
  • 1
  • 2
  • 10
11
votes
3 answers

android.database.CursorIndexOutOfBoundsException

The data access code in my Android app raises an exception. Here is the code that causes the exception: String getPost = "SELECT * FROM " + TABLE_POST + ";"; Cursor result = getReadableDatabase().rawQuery(getPost, null); List posts = new…
10
votes
3 answers

Default value when indexing outside of a numpy array, even with non-trivial indexing

Is it possible to look up entries from an nd array without throwing an IndexError? I'm hoping for something like: >>> a = np.arange(10) * 2 >>> a[[-4, 2, 8, 12]] IndexError >>> wrap(a, default=-1)[[-4, 2, 8, 12]] [-1, 4, 16, -1] >>> wrap(a,…
Eric
  • 95,302
  • 53
  • 242
  • 374
10
votes
5 answers

IndexOutOfBoundsException setSpan (0 ... 1) ends beyond length 0

I am using this library for material editText with label: https://github.com/rey5137/Material/wiki/Text-Field nice library :) but... i am using next code to check are entered symbols correct: private boolean hasCorrectSymbols(String input){ …
10
votes
5 answers

IndexOutOfBoundsException while updating a ListView in JavaFX

I got a problem with an IndexOutOfBoundsException while I want to update a ListView in JavaFX. What I need to do I have a ListView with elements that correspond to a small simulation. With a click on one list-element the graphical simulation updates…
mariusK
  • 103
  • 1
  • 1
  • 4
10
votes
1 answer

IndexOutOfBoundsException: charAt: 0 >= length 0 on some versions of Android

I am trying to get into using Java and Eclipse to make applications (currently using B4A, but want to expand my available resources, and ability to make libraries) When trying to implement a dialog using fragments, I have followed the example…
user2346305
  • 1,912
  • 14
  • 21
9
votes
1 answer

RecyclerView and java.lang.IndexOutOfBoundsException Invalid view holder adapter positionViewHolder

I have a RecyclerView that binds a grocery item. Adding the item works perfectly. However, when I try to delete the item the app crashes and I get the IndexOutOfBoundsException error. The problem I am facing is in my onBindViewHolder(). I tried to…
9
votes
4 answers

RecyclerView: IndexOutOfBoundsException Inconsistency detected. Invalid item position

Fatal Exception: java.lang.IndexOutOfBoundsException Inconsistency detected. Invalid item position 5(offset:5).state:24 This kind of crash happens too much!!! I get it in Fabric Crashlytics. Fatal Exception: java.lang.IndexOutOfBoundsException:…
8
votes
1 answer

Setting TextView text to static text crashes (rarely) with ArrayIndexOutOfBoundsException

By simply setting a TextViews text to a string defined in code (that never can be null) I sometimes get an ArrayIndexOutOfBoundsException, this only happens in my live app, I never had this issue on any test device yet... And it seems to happen…
prom85
  • 16,896
  • 17
  • 122
  • 242
8
votes
1 answer

Android: getChildDrawingOrder() returned invalid index 1 (child count is 1)

This is the stacktrace: Fatal Exception: java.lang.IndexOutOfBoundsException: getChildDrawingOrder() returned invalid index 1 (child count is 1) at android.view.ViewGroup.getAndVerifyPreorderedIndex(ViewGroup.java:1988) at…
Roudi
  • 1,249
  • 2
  • 12
  • 26
8
votes
2 answers

RecyclerView java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter position. Due to changing getItemCount()

I am getting a java.lang.IndexOutOfBoundsException: Inconsistency detected with the RecyclerView, but only when I seem to fling it. When I scroll slow enough it doesn't crash on me. I use my base adapter for many other subclasses but only certain…
The Nomad
  • 7,155
  • 14
  • 65
  • 100
8
votes
2 answers

JavaFX ComboBox change value causes IndexOutOfBoundsException

I want to include checks for my combobox to restrict "access" to some of the values. I could just remove those unaccessible items from the list, yes, but I'd like the user to see the other options, even if he can't select them (yet). Problem:…
leyren
  • 524
  • 6
  • 20
8
votes
2 answers

Python index out of range in list slicing

While this code will raise indexError: In [1]: lst = [1, 2, 3] In [2]: lst[3] IndexError: list index out of range Slicing the list with "out of range index" will not produce any error. In [3]: lst[3:] Out[3]: [] What is the rationale of this…
mclafee
  • 1,406
  • 3
  • 18
  • 25
8
votes
4 answers

Limiting character count of JavaFX TextField causes IndexOutOfBounds on Undo

I have the requirement to limit the number of characters a user can input into a TextField JavaFX control. I have extended TextField like so public class LengthLimitedTextField extends TextField { /** * @param maxCharacters The max allowed…
Display name
  • 1,109
  • 1
  • 15
  • 31
8
votes
4 answers

Way to pad an array to avoid index outside of bounds of array error

I expect to have at least 183 items in my list when I query it, but sometimes the result from my extract results in items count lower than 183. My current fix supposedly pads the array in the case that the count is less than 183. if…
Kobojunkie
  • 6,375
  • 31
  • 109
  • 164