IndexOutOfBoundsException ArrayList Error - java

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).

Related

What is the output of the following line of code?

What is the output of the following lines of code? (JAVA)
int nums[] = {1,2,3,4,5,6};
System.out.println(nums[1]+nums[3]);
I'm doing a practise revision sheet but I can't seem to workout the answer to this. EITHER - 7, 4, 5 OR 6.
ALSO when i try to put it into my Eclipse, it doesn't work.
The above code is first declaring an array of integer and then adding the second element (as in programming counting starts from zero), and 4 the element of the array.
If you want to run it on eclipse try this :
`
class Aartest
{
public static void main(String[] atg)
{
int nums[] = {1,32,1,2,31};
System.out.println(nums[1]+nums[3]);
}
}
`
The first line declares an array of integers. An array is a data structure which can hold more than 1 value at a time. To access the values you use indexes. The indexes start from 0. To access a value you write the array name followed by the index of the element in square brackets:
arrayName[index];
Index 0 gives you the first value in the array, index 1 - the second, and so on.
nums[1] will give you the second element in the array - 2.
nums[3] will give you the fourth element in the array - 4.
The second line will print the sum of nums[1] amd nums[3] which is 2 + 4 = 6.

Java code length -1 meaning [duplicate]

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

2D array row and column length

I'm studying 2D array right now, there is a part of 2D array I don't really understand. I will show my code and explain what part I don't understand.
My code:
public static void main(String[] args){
int[][]array={{1,2,3},{1,2,3},{1,2,3}};
}
public static printArray(int[][]a){
for(int row=0;row<a.length;row++){
for(int column=0;column<a[row].length;column++)
}
My question is for the second method of printArray. In the second for loop,what does column<a[row].lengthmeans?
This line gives the size of each row.
You know that
a[0]={1, 2, 3}
a[1]={1, 2, 3}
a[2]={1, 2, 3}
So, a[0].length = a[1].length = a[2].length = 3. Use of this is to ensure that we dont go Out Of Array Bounds.
Java doesn't have 2D arrays. Java has arrays of arrays. The second loop uses column < a[row].length to make sure that you don't iterate past the length of the row-th array. You need this to handle nested arrays of varying length.
That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException
A 2D array means that each element of the array is itself an array. The second loop allows you to loop through each {1,2,3} array (in your case). But to do that, you need the length of each array. That's what a[row].length provides.

Issue with ArrayList

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)

Why ArrayList giving unordered output?

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));

Categories