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<WeakReference<String>> exArrayList; exArrayList = new ArrayList<WeakReference<String>>(); exArrayList.add(new WeakReference<String>("Hello"));
I can now access the data with
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:
If this is a duplicate I haven’t found it with my keywords in google.
exArrayList.add(new WeakReference<String>("Hello"));is a bad example because
Stringliterals are never GC-ed
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
The data at
exArrayList.get(0) is the
WeakReference. It is not by itself a weak reference, so it will not be collected…
BUT the object referenced by
exArrayList.get(0) is weakly referenced, so it might be GCed at any time (of course, that requires that there are no strong references to that object).
data.get(0) won’t become
data.get(0).get() might become.
In other words, the list does not references the weak referenced object but the weak reference itself.
This is a bad idea as the other posters explained above (reference objects not freed). Use a WeakHashMap with the objects as keys and some dummy values (“” or Boolean.TRUE or similar).