What is WeakReference and WeakHashMap in Java?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
A WeakReference holds a reference to an object that does not prevent the object from being garbage collected. When only weak references point to an object, the GC is free to collect it. Useful for memory-sensitive caches — if memory is low, the cache entries are collected automatically. WeakHashMap is a Map implementation where keys are held with weak references. When a key is no longer referenced elsewhere in the program, the entry is automatically removed from the map. This makes WeakHashMap ideal for caches and canonicalized mappings (like the String pool concept) where you want the map entry to disappear when the key object is no longer used elsewhere in the application.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Java answers easy to follow.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?