ArrayList initial capacity problem (Index out of bounds Exception)
Code :
package newpackage;
import java.util.ArrayList;
public class NewClass {
public static void main(String[] args) {
ArrayList list = new ArrayList(5);
list.add(1, "ASD");
System.out.println(list.size());
}
}
whats wrong with the initialization of the arraylist object? its a basic assumption to anyone who will read the code,
a new ArrayList object is initialized with an initial capacity of 5, but why it doesnt have an initial capacity? i printed out the size of the array but the size was 0 , whats wrong?
Re: ArrayList initial capacity problem (Index out of bounds Exception)
Take a look at the API: ArrayList (Java Platform SE 6)
public void add(int index, E element)
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
Basically, capacity != size.
Re: ArrayList initial capacity problem (Index out of bounds Exception)
You need to read the API doc for the ArrayList's add method. It lists the exceptions that can be thrown and gives the reasons they are thrown. Your case is described there on the last line.
Re: ArrayList initial capacity problem (Index out of bounds Exception)
i guess the problem is how i look on the "words" itself (grammar)
capacity = limit of what it can hold (if im right)
size = physical dimension
i just took a little bit look on the API, and i cant find a direct solution for the problem i need to deal with,
actually, the code i posted is the problem i encountered on the part of a program im writing at the moment
i need to initialize an array with a specific size and insert something on the middle or somewhere in an index
is there a simple way to do this?
Re: ArrayList initial capacity problem (Index out of bounds Exception)
Quote:
insert something on the middle
The class you are using does not support that. It doesn't like empty slots.
If you use an array not an ArrayList, you can add items anywhere you want.
Re: ArrayList initial capacity problem (Index out of bounds Exception)
Quote:
The class you are using does not support that. It doesn't like empty slots
oh so theres the answer!! thanks it clears out the confusion , thanks so much!
i still have a way to insert something in a middle of an arraylist, i was planning when i was waiting for a clarification thanks thanks!!:o