I know there is a similar question has been answered in this post. However, I am still confused about whether java has the retain cycle problem as java also has the WeakReference class. So, are they serving the same purpose? What the difference between two of them?
Java does not have the "retain cycle problem".
This problem exists for systems that use reference counting, which the Java GC does not use.
Therefore in Java the WeakReference
class has nothing to do with those. It's simply a way to hold on to a reference to something while also not preventing it from being garbage collected
In other words, you can use it to remember an object as long as something else (strongly) references it.
This functionality is quite similar to what the weak
keyword does in Swift. However, as described above, reference cycles don't stop objects from being collected in Java, so WeakReference
is not needed in this specific case.
This SO question lists some practical uses for weak references and this question discusses uses specifically in an Java/Android environment.