Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SparseArray, check if key exists

I was implementing a Bitmap cache using a HashMap<Integer, Bitmap> and received the following warning in Eclipse:

Use new SparseArray(...) instead for better performance.

I've never heard of that class before, but inspecting it it doesn't seem to have a containsKey() method which I was calling on retrieval of a Bitmap from the cache to check if it exists in the cache, and if it doesn't, then add it.

Any ideas on the best way to check if the key already exists?

I guess I could change the code to use this overload and check for null?

Bitmap bitmap = cache.get(key, null);  
like image 974
magritte Avatar asked Sep 15 '12 22:09

magritte


1 Answers

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().

like image 73
Sam Avatar answered Oct 05 '22 07:10

Sam