SparseArray, check if key exists
You could use:
Bitmap bitmap = cache.get(key, null);
But understand that this is the same as get(key)
:
Bitmap bitmap = cache.get(key);
The best way to use get(key, default)
is to provide a generic default case, something to is a valid substitute when the key is not found.
But there is no good reason not to use if(get(key) != null)
as a quick replacement for contains()
.
Hence your value can be null in various situations, I'd suggest to useindexOfKey(int key)
Here is the indexOfKey(int key) reference.
Then just simply check for negative return value
if(mySparseArray.indexOfKey(int) < 0) { //Item does not exist. Do something relevant }
Quoting from documentation.
SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more efficient than using a HashMap to map Integers to Objects.
You can use get(int) which would also return null if key is not found. Like;
Bitmap bitmap = cache.get(key);