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 g开发者_如何学Carbage 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.
精彩评论