I'm trying to delete an object that I created in an ArrayList:
turtles.add(new Turtle());
I want to get rid of the last turtle in the ArrayList, something like this:
turtles.get(turtles.size() - 1) = null;
Any ideas? Simply removing from the list doesn't work, and Java won't let me nullify in the above way. I'm pretty sure there is only be a single reference to a given Turtle object, as they are only ever created in this way.
P.S: The Turtle class is a thread, in case that matters.
The JVM garbage collector automatically frees memory associated with an object when there are no remaining references.
In this case, removing it from the list will work perfectly fine unless you've kept another reference to that object.
If you've passed this thread to an ExecutorService to be ran (or called the start method) then it wont be destroyed until after the run method finishes. If that's the case and you want to stop the thread immediately, there are various ways to break out of the run method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With