简体   繁体   中英

IndexOutOfBoundsException when removing ArrayList element

I have this code right here (using lwjgl but that should be moot) to try and pause a game when pressing the esc key. I use an ArrayList with the keys to keep track of what is pressed and what isn't.

public List<Integer> keys = new ArrayList<Integer>();

public void get() {
    if (isKeyDown(KEY_ESCAPE) && !keys.contains(KEY_ESCAPE)) {
        keys.add(KEY_ESCAPE);
        keyEscape();
    }
}

public void rem() {
    if (!isKeyDown(KEY_ESCAPE) && keys.contains(KEY_ESCAPE))
        keys.remove(KEY_ESCAPE);
}

private void keyEscape() {
    Screen.paused ^= true;
}

This is called by the loop, which does get() and rem() one right after another in the loop, in that order. This gives me an awesome java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at keys.remove(KEY_ESCAPE); when I let go of ESC.

Anyone have any insight to share?

What is the value of KEY_ESCAPE?

It might be int with value 1 so instead of removing the object with that value, you remove the object at position 1 which apparently does not exist.

ArrayList.remove takes an int argument for the index where you want to remove your element. In your case, KEY_ESCAPE also happens to be an Integer.

In short you attempt to remove the Integer value of the escape key as the index of your ArrayList!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM