简体   繁体   中英

How does garbage collection work with collection objects?

I am curious how the GC works about the objects stored in the collection objects, such as ArrayList or Hashtable.

I have this ArrayList.

ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person("smith"));
persons.add(new Person("john"));
persons.add(new Person("harry"));
persons.add(new Person("nathan"));

Let's say that persons is still referenced by other object, but one of the Person objects stored inside the ArrayList persons is not referenced.

When the GC runs and looks for unreferenced objects, is it going to garbage collect the Person object that is not referenced or skip all the Person object, because the persons reference is still referenced by other object?

Any answer is appreciated.

All the Person objects stored in the ArrayList are referenced by the ArrayList itself, so as long as you maintain a reference to the ArrayList, there's an indirect reference to every Person object. The GC won't touch it.

If you want the GC to collect these stray Person objects, you can use a WeakReference to a Person in the ArrayList instead of a Person.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM