Gleyak iHope Gleyak iHope - 3 months ago 4
Java Question

Index Error with a For-Loop and a LinkedList

I am trying to make a little game on my own to get used to Java and I just had a problem with LinkedList Index. I found a way to patch my problem but I still don't understand why my first solution is not working. This code:

for (int i=0; i <= PlanetList.size(); i++)
g.drawImage(PlanetList.get(i).planetImage, PlanetList.get(i).xPos, PlanetList.get(i).yPos);

Gave me a java.lang.IndexOutOfBoundsException but this code:

for (int i=1; i <= PlanetList.size(); i++)
g.drawImage(PlanetList.get(i-1).planetImage, PlanetList.get(i-1).xPos, PlanetList.get(i-1).yPos);

The thing is ... my index start at 0 in both case. Why does the first gives me an Error?


Your last index in the first example is going above the allowed index range. For e.g., if the size of the list is 10, the allowed index range is [0 9]. In your first loop, it goes up to 10 (i <= PlanetList.size()). Change the terminal condition to i < PlanetList.size() to fix your issue.

The alternate is to use no indices to access elements in your list as @GhostCat has suggested:

for (Planet planet : PlanetList) {
    g.drawImage(planet.planetImage, planet.xPos, planet.yPos);

This is called for-each loop in Java