Junior — Middle
Can you explain what the WeakReference class is used for in Java?
sobes.tech AI
Answer from AI
The WeakReference class in Java is used to create weak references to objects. Unlike strong references, weak references do not prevent garbage collection: if an object is only accessible through weak references, it can be garbage collected.
This is useful, for example, for caching, where you want to store objects but not prevent their removal when memory is low. In Android, WeakReference is often used to hold references to Context or Activity to avoid memory leaks.
Example usage:
WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
MyObject obj = weakRef.get();
if (obj != null) {
// object is still accessible
} else {
// object has been garbage collected
}