0

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?

LulzCop
  • 121
  • 9
  • 2
    Why not use `boolean` flags rather having to check through the `ArrayList` every time? Seems unnecessarily expensive. – Quetzalcoatl May 14 '13 at 17:14
  • Consider using an `enum` for your key values instead of `Integer` values – John B May 14 '13 at 17:17
  • Related to but not a duplicate of http://stackoverflow.com/questions/34643366/java-arraylist-remove-object-indexoutofboundsexception – Raedwald Jan 07 '16 at 08:03

2 Answers2

6

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.

Lazarus Lazaridis
  • 5,415
  • 2
  • 18
  • 32
3

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!

Mena
  • 45,491
  • 11
  • 81
  • 98