Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Method of ArrayList throwing IndexOutOfBoundsException

While working on ArrayList, I found after setting the initial size of array using the constructor with initialCapacity, then use set() will throw an exception although the array is created, but size isn't set correctly.

Using ensureCapacity() won't work either because it is based on the elementData array instead of size.

There are other side effects because of the static DEFAULT_CAPACITY with ensureCapacity().

The only way to make this work is to use add() as many time as required after using the constructor.

Please check the code below.

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

    List test = new ArrayList(10);
    test.set(5, "test");
    System.out.println(test.size());
}

I am not sure why java is throwing this exception.

Behaviour I expected: test.size() should return 10 and set(5, ...) should work.

ACTUAL: throws an Exception IndexOutOfBoundsException.

So is it set method that is causing problem ?

like image 613
Sachin Sachdeva Avatar asked Dec 30 '15 09:12

Sachin Sachdeva


People also ask

What is set method in ArrayList?

The Java ArrayList set() method replaces the element present in a specified position with the specified element in an arraylist. The syntax of the set() method is: arraylist.set(int index, E element) Here, arraylist is an object of the ArrayList class.

What is IndexOutOfBoundsException in Java?

IndexOutOfBoundsException is a subclass of RuntimeException mean it is an unchecked exception which is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

How do you move values in an ArrayList?

Get the position (index) of the item using the indexOf() method of the ArrayList class. Remove it using the remove() method of the ArrayList class. Finally, add it to the index 0 using the add() method of the ArrayList class.

Is ArrayList FIFO or LIFO?

ArrayList is random access. You can insert and remove elements anywhere within the list. Yes, you can use this as a FIFO data structure, but it does not strictly enforce this behavior.


1 Answers

test.set(5, "test"); is the statement that throws this exception, since your ArrayList is empty (size() would return 0 if you got to that statement), and you can't set the i'th element if it doesn't already contain a value. You must add at least 6 elements to your ArrayList in order for test.set(5, "test"); to be valid.

new ArrayList(10) doesn't create an ArrayList whose size is 10. It creates an empty ArrayList whose initial capacity is 10.

like image 58
Eran Avatar answered Sep 17 '22 07:09

Eran