I was looking for information about objects, and on one site I found that

If you simply create an object and do not assign it to any variable, the Java machine will create it and immediately declare it garbage (unused object). And after a while, remove it in the process of "garbage collection."

Does this work if I use the collection?

ArrayList.add(new Object(...)) 

Because I can continue to use it after adding such an instance to ArrayList.

    2 answers 2

    Not. If an object is added to a collection, then in fact you assigned it to a collection item. As long as there is a link to an ArrayList containing this object, the garbage collector will not touch it.

      I will add that the JVM provides a special mechanism that allows garbage collection even if the object is in the collection. This is done through WeakReference

        MyObject myObject; myList = new ArrayList<WeakReference<MyObject>>(); myList.add(new WeakReference<MyObject>(myObject)); 

      in this case, the collector will be able to remove the myObject object even if it is in the collection.

      Sometimes it is useful.