This is a very basic example and I only used the existent methods.
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
// This should create an ArrayList of initial capacity 10
al.add(3,5); // Add 5 at index 3
al.add(7,2); // Add 2 at index 7
al.add(9,6); // Add 6 at index 9
System.out.println(al);
}
}
However, it throws the following exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 0
I don't know why the exception is thrown. It look perfectly legal to me.
You can't add a value at index 3 to an empty list. The capacity of an array list is the size of the underlying array; the indexes still have to be within the range of items actually added to the arraylist.
The relevant documentation is here
Note that it specifies an exception thrown if the index is greater than the size of the array ... which is different from the capacity.
The capacity does not mean there are 10 empty slots which you can assign your values to. This is not how ArrayList is supposed to work. You can put your values to the list only if the index is between 0 and list.size-1, this is why you are getting the exception.
Your code would try to find the element at index = 3, so that it could move it to next position. However, it can't find it as there is no element there.
See official docs for add(int index, E element)
it throws java.lang.IndexOutOfBoundsException: if the index is out of range (index < 0 || index > size())
Check that does your case satisfies conditions or not !!!
This will work
ArrayList<Integer> al = new ArrayList<Integer>();
// This should create an ArrayList of initial capacity 10
al.add(0,5); // Add 5 at index 0
al.add(1,2); // Add 2 at index 1
System.out.println(al);
Your case size() is 0. So you cannot put directly at al.add(3,5)
Related
This question already has answers here:
Does a primitive array length reflect the allocated size or the number of assigned elements?
(17 answers)
What does arrays.length -1 mean in Java?
(1 answer)
How do you determine the legal index range for an array?
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
class Zillion {
private int zilly[];
public Zillion(int size){
zilly = new int[size];
}
public void increment(){
int i=zilly.length -1;
while(i>=0){
if(zilly[i]!=9){
zilly[i]+=1;
i=-1;
}
else{
zilly[i]=0;
i--;
}
}
}
I just got a basic java code like this and do not know what length -1 means at this part (int i=zilly.length -1;).
Can someone please explain this ?
The size of array is the number of elements in this array, but The first index of arrays is 0. For example :
int zilly[] = {1, 2, 3, 4}
In this example :
zilly.size return : 4
But zilly[4] not exist because the index of the first element is 0
zilly.[zilly.size - 1] return the last element (4).
Hope it helps.
nameOfTable.lenght return the number of element
the first index of Arrays start with 0 ==> (1st - 1 = 0) ,
so the last index is n - 1
int i=zilly.length -1; is the last index of the array, because arrays start at index 0.
A side note, the formatting of this code be improved to better portray what it's doing, for example the line that confused you could be.
int i = zilly.length - 1; simply spacing out the statement correctly makes it a bit easier to understand.
zilly.length -1 defines itself. Total array length (size) -1.
Since the first index of array starts with 0 so the last item is at position n-1 where n is the size of array.
In Java indexing of arrays starts from 0. Therefore the last element of arrays is accessed by zilly[zilly.length - 1]. If you try to access it this way:
zilly[zilly.length]
you will get an out of bounds exception.
The while loop in your code starts from the last index and iterates down the very first element.
zilly.length gives the length of the array, i.e. the number of elements in it.
zilly.length-1 gives the last index of the array because the count of the array begins from 0.
So basically you are iterating in a descending order, i.e. from the last element of the array to the first element of the array.
It means that we want to get the last index in the array.
And then we loop over the array from end to start.
zilly.length it's the array size - but the array's index starts from 0 so the last index is zilly.length-1
I am facing Array Index OutboundException when runs the code..
My code here
public void putValuesForDeleteAction(HashMap map ,Object[] colNames,Object[] colValues,Object[] colDataTypes){
try{
if(colNames!=null && colNames.length > 0 && colValues!=null && colValues.length >0 &&
colDataTypes!=null && colDataTypes.length >0){
int i = 0;
i = colNames.length ;
colNames[i]="LAST_UPDATE_BY";
colValues[i]=(String)map.get("LAST_UPDATE_BY");
colDataTypes[i]="VARCHAR2";
i++;
colNames[i]="LAST_UPDATE_DATE";
colValues[i]=(String)map.get("LAST_UPDATE_DATE");
colDataTypes[i]="TIMESTAMP";
System.out.println("mapValues is "+map);
}else{
// do nothing
}
}catch(Exception e){
e.printStackTrace();
}
}
Error logs
2014-09-17 10:47:51.026 ERROR [STDERR] java.lang.ArrayIndexOutOfBoundsException: 9
ArrayIndexOutOfBoundException means it does not found any element at index position which you specifying
in your case you first assign object array length to i by i = colNames.length ;
suppose your array length is 4
means your array last index is 3 because index start from 0,1,2,3 total length 4
so replace
i = colNames.length ;
with
i = colNames.length - 1 ;
and again you are doing i++ which is again wrong statement
conclusion is ArrayIndexOutOfBoundException occurs when your i > array length
You can use System.arrayCopy to copy existing array to an array of more size and aviod the exception.
Below copyFrom is the original array and copyTo is the destination array of larger size.
System.arrayCopy(copyFrom, 0, copyTo, 0, copyFrom.length);
This piece of below code is causing problem.
colNames[i] = "LAST_UPDATE_BY";
colValues[i] = map.get("LAST_UPDATE_BY");
colDataTypes[i] = "VARCHAR2";
colNames[i] = "LAST_UPDATE_DATE";
colValues[i] = map.get("LAST_UPDATE_DATE");
colDataTypes[i] = "TIMESTAMP";
Once value of i is more than the array length, it will give this exception.
java.lang.ArrayIndexOutOfBoundsException
Eg: suppose length of any array is 2, so at max you can access [0] and [1], but if you try to access [2], it will throw the above exception.
Solution to your problem
Since you are trying to add new elements in all the three arrays, you must increase or set the size before hand.
Including on #Aryan request, just run below program and analyze
public static void main(String[] args) {
// declaring array of size 2, ie it will contain max 2 elements
String[] myArray = new String[2];
System.out.println("accessing 1 element");
System.out.println(myArray[0]);
System.out.println("accessing 2 element");
System.out.println(myArray[1]);
// while accessing 3rd element, it will give error, since size is defines as 2.
System.out.println("accessing 3 element");
System.out.println(myArray[2]);
}
I would suggest you use an ArrayList as you won't have to worry
about the length anymore. Once created, you can't modify an array
size:
An array is a container object that holds a fixed number of values
of a single type. The length of an array is established when the array
is created. After creation, its length is fixed.
I have written java program, to add integer in ArrayList and remove that integer from ArrayList . but it not giving me proper result. here is my code..
public static void main(String args[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(6);
a.add(7);
a.add(8);
a.add(9);
for(int i=0;i<=a.size();i++)
{
System.out.println("Removed Elements=>"+a.remove(i));
}
}
it giving me output as follows
Removed Elements=>6
Removed Elements=>8
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
why i am getting output like this?
Your array:
a[0]=6
a[1]=7 <-- i
a[2]=8
a[3]=9
Then you remove at 1, and i increments to 2:
a[0]=6
a[1]=8
a[2]=9 <-- i
Remember that array indexes start at 0, so the last element is at a.length - 1
You get your exception because the loop condition i <= a.size(), so at the final iteration:
a[0] = 7
a[1] = 9
2 <-- i
When you remove items from a list, or any collection, you either use the iterator, or you use a reverse loop like this.
for (int i = (a.size() - 1); i >= 0; i--) {
System.out.println("Removed Elements=>" + a.remove(i));
}
By going backwards, you avoid the incrementing by 2 problem that has been documented in the other answers.
for first iteration, a.remove(i) causes the element 7 to be removed which is returned by remove method.
For second iteration, the size of list is 3 and you are removing the element at index 2 which is 9. SO remove method returns 9.
In short
Iteration | Size of list | index being removed | element removed
----------+--------------+---------------------+----------------
1 | 4 | 1 | 7
2 | 3 | 2 | 9
If you want a forward loop to remove all elements you could use the following code:
while(!a.isEmpty())
{
System.out.println("Removed Elements=>" + a.remove(0));
}
Your problem is that, as you remove elements, you resize the ArrayList. However, your loop counter is not updated, so you iterate past the bounds of the ArrayList.
ArrayList.remove(index) removes the element from the array, not just the contents of the ArrayList, but it actually resizes your ArrayList as you remove items.
First you remove the 1st element of the ArrayList.
Removed Elements=>6
Here the list has been resized from size 4 to size three. Now the element at index 0 is 7.
Next, you step to the element at index 1. This is the number 8.
Removed Elements=>8
Here the ArrayList has been resized to length 2. So there are only elements at index 0 and 1.
Next you step to index 2.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
There is no index 2, so you get an IndexOutOfBoundsException.
the index starts with 0 and ends with size - 1
your loop goes from 1 to size - 2
ArrayList indexes start at zero, but your loop starts removing at 1. After adding the elements your arraylist looks like this:
0 - 6
1 - 7
2 - 8
3 - 9
Because your loop starts counting at 1, you will first remove the element labeled 1, which is 7.
The list will then look like this:
0 - 6
1 - 8
2 - 9
Then the loop will remove the element labeled 2, which is now 9.
So the two mistakes are starting at 1 instead of 0, and incrementing the counter after something has been removed (all elements after the removed element will shift down).
In the first iteration , i starts from 1, so your second element is removed ie. 7. Now list has
6
8
9
Next iteration is 2, so third element 9 is removed.
Your output is correct : Here is the explaination.
When the loop is executed for the first time, value of i will be 1. and it execute the statement a.remove(1). after removing the value 7 which is at place a[1], '8will be ata[1]'s place. After that i is incremented and becomes 2 and it removes the element a[2] which is 9.
This is simple logic:
First Iteration i=1:
a[0]=6,
a[1]=7,
a[2]=8;
a[3]=9;
Remove a[i] i.e a[1] removes 7
Second Iteration i=2:
a[0]=6
a[1]=7
a[2]=9
Remove a[i] removes 9
The value of i in the loop goes through the following values
0
1
2
3
4
The array has index with values 0 , 1 , 2 , 3
The loop will run for values 0,1,2,3,4
The array is not displayed ordered bcoz when one value is removed the next value is available at index 0
At i=2 , the size of array is 2 and max index is 1 , and hence IndexOutofBound exception is encountered
use the following loop :
while(a.size()>0)
{
System.out.println("Removed Elements=>"+a.remove(0));
}
whenever you remove an element from arraylist it deletes element at specified location.and this should be noted each time the size of arraylist decreases.
I dont understand what are you trying to remove. If you wan to clear list just call clear() method. If you are trying to remove objects contained in list, than you should know that ArrayList contains objects, not primitive ints. When you add them your are doing the following:
a.add(Integer.valueOf(6));
And there are two remove methods in ArrayList:
remove(Object o) //Removes the first occurrence of the specified element from this list
and the one you are calling:
remove(int index) //Removes the element at the specified position in this list
May be you should call first one:
a.remove(Integer.valueOf(i));
This is my current progress on a project. I am trying to implement this ArrayList stuff but file continues to trow the same exception.
import java.util.*;
public class Numerican{
public static void main( String [] args ){
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>(10);
int count = input.nextInt() * 2;
while (count > 0){
array.add( 0 );
count = count - 1;
array.add(count, 2);
}
array.add(2, input.nextInt());
System.out.println(array.get(2));
}
}
It was my understanding that = new ArrayList<Integer>(10); would set the array size to 10. Did I do something wrong?
= new ArrayList<Integer>(10);
This line initializes the CAPACITY to 10, meaning the memory is allocated in the backend, but as far as you are concerned, the array is still empty.
Javadoc -
public ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
This is why the calls to add might fail, if you try to add beyond the size of the ArrayList.
p.s. remember that add function takes index first and then element, when using the 2 parameter variant.
Edit:
ArrayList has 2 different member variables, size and capacity. Capacity is how much memory is allocated, size is how many elements are inserted by programmer.
Here, Capacity = 10, Size = 0;
According to the javadocs:
Constructs an empty list with the specified initial capacity.
Note that the ArrayList is empty (i.e. does not contain any items). The value indicates the capacity of the ArrayList which is the number of elements which can be added before more memory must be allocated.
On the other hand, calling add() actually adds an item to the ArrayList. In your example, array.add( 0 ); adds a 0 at the end of the list and array.add(count, 2); adds a 2 at index count. I suspect the problem is that count is not a valid index in your ArrayList. You should check what its value is by inserting an SOP or using a debugger.
count maybe >= 10, maybe souce code can answer you question:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
rangeCheckForAdd():
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
if the index is out of range (index < 0 || index > size()) IndexOutOfBoundsException will be thrown.
So i think you are accessing index > size() of the list.
size() ===> Returns the number of elements in this list.
array.add(2, input.nextInt()); here is the possible exception when your list size is 1...
From my understanding of ArrayList, you need to add items to the list in a sequential index.
i.e. You cannot add an item to the 7th index position if 1 to 6 have not been filled in.
ArrayList.add(indexPosition, element);
If you add elements to the list, starting at indexPosition 0, and increasing the indexPosition by 1 each time, it should work.
Ex.
int i = 0;
(while i < 10){
array.add(i, numberToAdd);
i++; }
Hey seems like your Problem is because of the line
array.add(count, 2);
adds a 2 at index count
For example your input size is 5 then array.add(9,2); the array size is only 1 by that time as capacity and size are two different parameters for a ArrayList. So you can use a for loop instead of while to insert your values
for(int i=0; i<count;i++)
{
array.add(i,2);
}
I'm writing a basic java card game but I'm getting a
java.lang.IndexOutOfBoundsException: Index: 6, Size 6 (in java.util.ArrayList error on this bit of code, could you help me please?
public void simple() {
if (cards.get(cards.size()-1).getSuit().equals(cards.get(cards.size()).getSuit())) {
int last=cards.size()-1;
Card c=cards.remove(last);
cards.set(last-1,c);
}
else {
System.out.println("hi");
}
}
Calling cards.get(cards.size()) will fail every time.
This is because they're 0 indexed. So if you have size 6, your indexes are 0,1,2,3,4,5.
If you want the last two cards, use cards.get(cards.size()-2) and cards.get(cards.size()-1).
Your problem occurs on your second line with the code cards.get(cards.size()).
Indices for lists in Java start at 0 so cards.size() would, by definition, be accessing an element outside the cards collection and throwing the IndexOutOfBoundsException. The last element in cards will always be atcards.size()-1`.
Here's your problem: cards.get(cards.size())
An ArrayList is just like an array - if it has 6 elements in it, then the index of the last item is 5 (since arrays start at index 0, not 1).