简体   繁体   中英

ArrayList IndexOutOfBoundsException despite adding within the capacity of the list

I have following code

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(1, 555);
}

and it is initialize with 10 elements but i am getting exception

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0   
   at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)  
   at java.util.ArrayList.add(ArrayList.java:426)   
   at ListTest.main(ListTest.java:9)

while below code working fine

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(0, 555);
}

Why can someone explain me ? and How to fix the issue i want to put item in 1th,2nd or 5th position in my code ?

it is initialize with 10 elements

No, it isn't. It's initialized with an internal buffer size of 10, but that's largely an implementation detail. The size of the list is still 0, as you can confirm by printing out list.size() before your add call.

It's important to differentiate between "amount of space in the buffer ready to accept more elements without copying" and "the size of the list". From the add documentation :

Throws:
IndexOutOfBoundsException - if the index is out of range ( index < 0 || index > size() )

Here size() is 0, and 1 > 0 , hence the exception.

You should always check the documentation before assuming that it's the framework (or compiler) that's wrong.

How to fix the issue i want to put item in 1th,2nd or 5th position in my code?

You either need to add enough elements first, eg

for (int i = 0; i < 10; i++) {
    list.add(null);
}
list.set(1, 555);
list.set(2, 500);
list.set(5, 200);

Note that these are set operations, not add - it's not clear whether you really want to insert or modify.

Or you should potentially use an array instead. For example:

int[] array = new int[10];
array[1] = 555;
array[2] = 500;
array[5] = 200;

In both cases, it's important to understand that indexes are 0-based - so list.set(1, 555) changes the second element of the list. You'd want list.set(0, 555) to change the first element. The same applies for arrays.

Here is your answer : The code snippet of public void add(int index, E element) {

 if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

basically, when you do new ArrayList() the size of the list will be 0 . Since your index is greater than size , you get IndexOutOfBoundsException

You have to add elements to a list gradually, the list will be extended automatically.

If you want to add a certain element on a specific position, and you know the length of the amount of items you want; you can use an Integer array and convert that to a list afterwards, for example

public static void main(String []args){
    Integer []fixedLengthArray = new Integer[5];
    fixedLengthArray[1] = 3;
    List<Integer> intList = Arrays.asList(fixedLengthArray);
    for(int i= 0;i<intList.size();i++)System.out.println("Value of index "+i+":"+intList.get(i));
}

Output will be:

Value of index 0:null Value of index 1:3 Value of index 2:null Value of index 3:null Value of index 4:null

While the method is called add it is really an insert operation. You are essentially telling Java 'put this after the first item in the list' and Java is replying 'there is no first item in the list'.

Fist of all it will give a compilation error on

List<Integer> list = new ArrayList<>(); 

for ArrayList<Integer>()

and it is initialize with 10 elements Where you did that.?

What we see, It's not initialized with 10 elements actually its empty that why when you try to add something on index 1 it's giving IndexOutOfBound on line

list.add(0, 555);
public static void main(String[] args) {
     List<Integer> list = new ArrayList<>(1);
     list.add(0, 555);
}

This code will help. This add method with index can be invoke if there is data in that index position.

Because, at the second code piece zero is the first index. But at the first code piece one is not the first index and there isn't any memory allocation for your index.

You have to do like that;

public static void main(String[] args) {
             List<Integer> list = new ArrayList<>();
             list.add(0, 555); //Correct
             list.add(1, 55); //Correct
             list.add(2, 525); //Correct
             list.add(5, 55235); // Not-correct  ! 
        }

or

Create a list and assign all indexes with a default value. Then use the index which you want.

public static void main(String[] args) {
             List<Integer> list = new ArrayList<>();
             for(int i=0; i<10; i++)
             {
                 list.add(null);//or default value like -99
              }
             list.add(0, 555); //Correct
             list.add(1, 55); //Correct
             list.add(2, 525); //Correct
             list.add(5, 55235); //correct  ! 
        }

or

Just do that

int[] array = new int[10];

It's because you will not get fruits from the tree untill you plant the Tree as simple as that .

When you initialised the list , it is an empty list , which can be verified by list.size() which will return 0 , Now you have 0 elements in the list and you are trying to access the 1 index , So it is giving you the exception

From Java Docs

void add(int index,
       E element)

Inserts the specified element at the specified position in this list(optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

and it Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

Your 'list' is still an ArrayList So you can not change its index (Normally, index of an arraylist must be started at 0). So that the reason why when you put " list.add(1,555) " it throw an error.

Just simple list.add(555)

Instead of ArrayList you can use Map, SortedMap, HashMap, TreeMap. Those will store values as a pair Key - Value.

Hashtable<Integer,Integer> list = new Hashtable<>();
list.put(1, 555);

HashMap<Integer,Integer> list2 = new HashMap<Integer,Integer>();
list2.put(3, 555);

Hope this help!

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