Search code examples
javaandroidarraylistgarbage-collectionweak-references

android - java - WeakReferences with an ArrayList?


I know that with a WeakReference, if I make a WeakReference to something that unless there's a direct reference to it that it will be Garbage Collected with the next GC cycle. My question becomes, what if I make an ArrayList of WeakReferences?

For example:

ArrayList<WeakReference<String>> exArrayList;
exArrayList = new ArrayList<WeakReference<String>>();
exArrayList.add(new WeakReference<String>("Hello"));

I can now access the data with exArrayList.get(0).get().

My question becomes: This is WeakReference data, will the data located at exArrayList.get(0) be GC'd with the next GC cycle? (even IF I don't make another direct reference to it) or will this particular reference stick around until the arraylist is emptied? (eg: exArrayList.clear();).

If this is a duplicate I haven't found it with my keywords in google.


Solution

    1. exArrayList.add(new WeakReference<String>("Hello")); is a bad example because String literals are never GC-ed

    2. if it were e.g. exArrayList.add(new WeakReference<Object>(new Object())); then after a GC the object would be GC-ed, but exArrayList.get(0) would still return WeakReference, though exArrayList.get(0).get() would return null