How would I create function to select newest object in array list

For a project, I am making a game where users can press a key to add legos. However, I also want there to be a key for them to delete the last lego placed. Right now I can delete the first lego placed using Legos.remove(0); but this is not really ideal. I was thinking of replacing the 0 with a variable, maybe just called newestLego. And then I could I set the newestLego to retrieve the last lego object placed? Somehow? Or is there a simpler way to do this that I am unaware of… I am very much new to coding. Thank you for any help or insight you can provide!

public void keyTyped() { 
  if (key == 'l' && mode == 1) { //if l key pressed and the mode is toyInteraction, 1, add a lego
    //println("l key pressed");
    index++; //increase with creation
    Lego lego = new Lego(mouseX, mouseY, index); //places lego at mouse clicked location
    Legos.add(lego);
  }
  if (key == 'c' && mode == 1) { //if the key pressed is 'c,' all legos are removed 
    //println("c key pressed");
    Legos.clear();
    reset(); 
  } else if (key == 'r' && mode == 1) { //if the key pressed is 'r,' remove a lego
    //println("r key pressed");
    index--; //decrease with deletion
    Legos.remove(0);
  }
}
1 Like

Legos.remove(Legos.size() - 1)

should do the trick

2 Likes

That did totally work! Thanks for your help!