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

**URL:** <https://discourse.processing.org/t/how-would-i-create-function-to-select-newest-object-in-array-list/21925>\
**Category:** Coding Questions\
**Created:** [June 16, 2020, 5:29pm UTC](https://discourse.processing.org/t/how-would-i-create-function-to-select-newest-object-in-array-list/21925 "2020-06-16T17:29:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![s.k9](https://avatars.discourse-cdn.com/v4/letter/s/5f9b8f/32.png) [@s.k9](https://discourse.processing.org/u/s.k9)\
**Post date:** [June 16, 2020, 5:29pm UTC](https://discourse.processing.org/t/how-would-i-create-function-to-select-newest-object-in-array-list/21925/1 "2020-06-16T17:29:26Z")

</div>

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!

```auto
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);
  }
}

```

---

<div class="post-metadata">

**Author:** ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)\
**Post date:** [June 16, 2020, 5:37pm UTC](https://discourse.processing.org/t/how-would-i-create-function-to-select-newest-object-in-array-list/21925/2 "2020-06-16T17:37:14Z")

</div>

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

should do the trick

---

<div class="post-metadata">

**Author:** ![s.k9](https://avatars.discourse-cdn.com/v4/letter/s/5f9b8f/32.png) [@s.k9](https://discourse.processing.org/u/s.k9)\
**Post date:** [June 16, 2020, 5:39pm UTC](https://discourse.processing.org/t/how-would-i-create-function-to-select-newest-object-in-array-list/21925/3 "2020-06-16T17:39:30Z")

</div>

That did totally work! Thanks for your help!
