简体   繁体   中英

Is Java WeakReference the same as the swift weak keyword?

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.

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