We've not covered ArrayLists only Arrays and 2D arrays. What I need to do is be able to read from an ArrayList from another class. The main aim is to read from them in a for loop and use the values stored in them to display items. However, I have made this quick program to test it out and keep getting this error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at Main.Main(Main.java:14)
Here is my code
import java.util.ArrayList;
public class Main
{
public static void Main()
{
System.out.println("Test");
ArrayList <Objects> xcoords = new ArrayList<Objects>();
for( int x = 1 ; x < xcoords.size() ; x++ )
{
System.out.println(xcoords.get(x));
}
}
}
And then the class where the ArrayList is
import java.util.ArrayList;
public class Objects
{
public void xco()
{
ArrayList xcoords = new ArrayList();
//X coords
//Destroyable
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
xcoords.add(5);
xcoords.add(25);
xcoords.add(5);
//Static Walls
xcoords.add(600);
xcoords.add(400);
xcoords.add(600);
}
}
If someone can point me in the correct direction it would be so valuable. I've tried to debug however I can get anything helpful.
Thanks in advance.
You have an
IndexOutOfBoundsException
which means that you are trying to access an element in an array which is not existing.But in your code posted here you are not accessing an array at all (your for loop will not execute once because the list is empty), which means that your exception is thrown somewhere else.
But also your code doesn't make any sense. I refactored it for you while staying as close to your code as possible, so you can see how it could work:
Strictly speaking, the exception is due to indexing location 1 of an
ArrayList
with 0 elements. Notice where you start you for loop index variablex
. But consider this line:xcoords
points to a new, emptyArrayList
, not the one you created in class Objects. To get thatArrayList
, change the methodxco
likethen, in your
main
methodHere you're simply creating two completely unrelated lists. Either have the array list be a property of the
Objects
class and retrieve it through an instance method, or return it from an instance or static method, or make the property static. IMO the first two are preferable in most situations.Then to use it:
Also, your
List
should be ofInteger
, not ofObjects
, which would create a collection holding instances ofObjects
. You may want to take a step back and relate lists to arrays in a better way--you wouldn't create an array ofObjects
, would you? No, you'd have an array ofint
orInteger
.Also, there's
Arrays.asList
.