BReynolds
BReynolds

Reputation: 333

Java ArrayList - Not Setting Existing Element

When I try:

//Util.java

public static ArrayList<Sprite> Load(String[] path, int numOfFiles){
    ArrayList<Sprite> sprites = new ArrayList<Sprite>(numOfFiles);
    Texture texture;
    Sprite sprite;
    for(int i = 0; i < numOfFiles; i++){
        texture = new Texture(Gdx.files.internal(path[i]));
        texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
        sprite = new Sprite(texture);
        sprite.flip(false, true);
        sprites.set(i, sprite);
    }
    return sprites;
}

I get an error:

Exception in thread "LWJGL Application" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

If I call:

//TheGame.java

ArrayList<Sprite> sprites;
String[] filenames = {"a.png", "b.png", "c.png"};

sprites = new ArrayList<Sprite>();

sprites.addAll(Util.Load(filenames, 3));

It should work becausenumOfFilesis3. I would prefer to use it the way I want. Why is it doing this?

I have changed it to this in the meantime, which works just fine.

//Util.java

public static ArrayList<Sprite> Load(String[] path, int numOfFiles){
    ArrayList<Sprite> sprites = new ArrayList<Sprite>();
    Texture texture;
    Sprite sprite;
    for(int i = 0; i < numOfFiles; i++){
        texture = new Texture(Gdx.files.internal(path[i]));
        texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
        sprite = new Sprite(texture);
        sprite.flip(false, true);
        sprites.add(sprite);
    }
    return sprites;
}

Upvotes: 0

Views: 130

Answers (3)

Salih Erikci
Salih Erikci

Reputation: 5087

You get IndexOutOfBoundsException because there was no element inside ArrayList when you try to replace an item by sprites.set(i, sprite);

Upvotes: 0

Boann
Boann

Reputation: 50041

The constructor new ArrayList<Sprite>(numOfFiles) does not create an ArrayList of size numOfFiles. It creates an ArrayList of size 0, having an internal array whose capacity is numOfFiles. Since the list is empty, you can't set an element, since there is no element to set. The only purpose in providing a number to the ArrayList constructor is as an optimization to reduce internal array reallocation when the list grows.

The second version of the code in your question is correct. That's the way you should write it. You can optionally pass numOfFiles to the ArrayList constructor as an optimization to make sure it has an array of exactly the needed size, but you must still call add instead of set.

Upvotes: 4

anubhava
anubhava

Reputation: 785721

As per Javadoc of ArrayList set:

Replaces the element at the specified position in this list with the specified element.

That is reason of IndexOutOfBoundsException since you're not calling add before calling set. In short your list is still empty when set method is invoked.

Upvotes: 1

Related Questions