4

I have to implement the classification of somehting like Hashmap with two keys and a value, let's say Hashmap<K1, K2, V>, where the two keys are integers and the value is a generic MyObject defined by me.

I read this, this, and this post, and I also know that guava project offers the table interface, but I don't want to use external libraries (if not strictly necessary) to keep my project smaller as possible. So I decided to use SparseArrays: I thought that this was the better choice because my keys are int and are not necessarily starting from zero and increasing.

I do this initializing:

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

Now let's go to the point. Can I do this kind of operation:

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

or should I do something like:

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

In other words: Do I initialize both SparseArrays with this single line?

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

Do you think there are better implementations for my case?

Community
  • 1
  • 1
The Good Giant
  • 1,740
  • 2
  • 19
  • 35

2 Answers2

1

If you have two keys and one value, I would just use a normal HashMap or SparseArray and will combine those two keys into one value. Let's say you have one key which is String and one which is Long so your map key will be: (strKey + longKey).hashCode(). You can use it as Integer and save it into SparseArray or as String and use HashMap.

Elad92
  • 2,471
  • 4
  • 22
  • 36
  • both of the keys are int, the only alternative solution I thought was using normal 'Hashmap' or 'SparseArray' and use as a key a string composed by the two int: int key1 = 3; int key2 = 2; String Key = "key1: " + key1 + " key: " + key2; But I found it a bit tricky.. – The Good Giant Mar 22 '13 at 14:55
  • Why do you think it's tricky? `String key = key1 + key2` (In our case the key String should be "32"), you can use `SparseArray` by doing `key.hashCode()` or `HashMap` using the `String` itslef. – Elad92 Mar 22 '13 at 15:01
0

Having tow nested SparseArray is against the purpose of having SparseArray in the first place since you will allocate a new SparseArray for each unique first key in your key pairs.

A good solution for that would be by using hashmap and use a key object that takes two int values (Point for example) or an object that you define that simply holds two keys.

Mr.Me
  • 9,192
  • 5
  • 39
  • 51