1

In Java, a HashMap object that is specified as a key is not eligible for garbage collection. A WeakHashMap object that is specified as a key is still eligible for garbage collection

My question is in Android, what is the behavior of SparseArray in terms of garbage collection? Is it more like HashMap or more like WeakHashMap

Richard Hu
  • 811
  • 5
  • 18
  • _In Java, a HashMap object that is specified as a key is not eligible for garbage collection. A WeakHashMap object that is specified as a key is still eligible for garbage collection_ - this makes _very_ little sense. – Eugene Feb 13 '20 at 14:35
  • what is eligible or not for GC is based on _reachability_; be that strong (by default) for `HashMap` or weak for `WeakHashMap`. until you understand what this means - you will not be able to correctly use them – Eugene Feb 13 '20 at 14:41

1 Answers1

0

A SparseArray works very similarly to a Map<Integer, Object>.

The key differences are that it does not cast or auto-box anything, and that it uses a binary search to find entries not a hash lookup.

The references inside are strong references, like the majority in Java.

If you wanted, you could store WeakReferences in a SparseArray, just like you could any other Object.

alex
  • 6,359
  • 1
  • 23
  • 21