Initializing Android SparseArray <SparseArray <Object>>

I have to implement somehting classification as a Hashmap with two keys and a value, let Hashmap<K1, K2, V> , where the two keys are integers, and the value is the common MyObject defined by me.

I read this , this and this , and I also know that the guava project offers a table interface , but I do not want to use external libraries (if not strictly necessary) so that my project is as small as possible. Therefore, I decided to use SparseArrays: I thought it was the best choice, because my keys are int and do not necessarily start from scratch and increase.

I am doing this initialization:

 SparseArray<SparseArray<MyObject>> myObjectSparseArray = new SparseArray<SparseArray<MyObject>>(); 

Now release to the point. Can I do this operation:

 MyObject myObject = new MyObject(); myObjectSparseArray.get(3).put(2,myObject); 

or I need to do something like:

 MyObject myObject = new MyObject(); myObjectSparseArray.put(3, new SparseArray<MyObject>()); myObjectSparseArray.get(3).put(2,myObject) 

In other words: Am I initializing both SparseArrays with this single line?

 SparseArray<SparseArray<MyObject>> myObjectSparseArray = new SparseArray<SparseArray<MyObject>>() 

Do you think there are more efficient implementations for my case?

+4
source share
2 answers

If you have two keys and one value, I would just use a regular HashMap or SparseArray and combine these two keys into one value. Say you have one key that is String and one that is Long , so your map key will be: (strKey + longKey).hashCode() . You can use it as an Integer and save it in a SparseArray or as a String and use a HashMap .

+1
source

Having towed nested SparseArray contrary to the purpose of SparseArray in the first place, since you will SparseArray new SparseArray for each unique first key in your key pairs.

A good solution for this would be to use hashmap and use a key object that takes two int values ​​( Point ) or an object that you define that just contains two keys.

0
source

All Articles