Search code examples
androidhashmapandroid-sparsearray

Android: HashMap vs WeakHashMap vs SparseArray in terms of garbage collection


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


Solution

  • 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.