Delete the object created in ArrayList in Java loop
I'm trying to delete the objects I created in ArrayList:
turtles.add(new Turtle());
I want to get rid of the last turtle in ArrayList, as follows:
turtles.get(turtles.size() - 1) = null;
Any ideas? Simply deleting from the list doesn't work. Java won't invalidate me in the above way I'm pretty sure there's only one reference to a given turtle object because they're just created this way
P. S: the turtle class is a thread, if important
Solution
When there are no references left, the JVM garbage collector automatically frees the memory associated with the object
In this case, it is perfectly normal to remove it from the list unless you keep another reference to the object
If you have passed this thread to the executorservice (or start method) to run, it will not be destroyed until the run method completes If this is the case and you want to stop the thread immediately, there are several ways to break through the run method