3

I have been playing very well with sparseArray until today. Now it looks sparseArray will not repay my love :(

I have to maintain the order of my objects I am storing in a sparseArray. There is only one method setValueAt that don't allow to set the key. key is important for me.

Tell me what is work around? Should I hack the source? Or If any one can help with a custom method which I can add in a custom sparseArray class of my own i.e I will code MySparseArray inheriting from sparseArray to add my that method. I need to add an object with a specific key at the last index or at the end of my sparseArray.

ahmadalibaloch
  • 5,851
  • 2
  • 50
  • 59
  • Not everyone here knows every fancy little class library any other user is using, so you might paste some example code of yours producing the problem. – Smutje Feb 17 '14 at 18:30
  • 1
    Hi baby :P. SparseArray is not a part of some library. Its there in Android SDK. You know Android is a custom implementation of Java. It has somethings that Java don't have and somethings lacking which Java have. Moreover, its recommended to use SparseArray whenever possible. – ahmadalibaloch Feb 17 '14 at 18:33

2 Answers2

1

Based on the documentations for keyAt I believe this should be how you add to the "end" of the SparseArray.

    SparseArray<Object> myArray = new SparseArray<Object>();
    myArray.put(myArray.keyAt(myArray.size()-1) + 1, new Object());

Documentation:

The keys corresponding to indices in ascending order are guaranteed to be in ascending order, e.g., keyAt(0) will return the smallest key and keyAt(size()-1) will return the largest key.

JRomero
  • 4,878
  • 1
  • 27
  • 49
0

According to http://developer.android.com/reference/android/util/SparseArray.html, there is the append(int key, E value) method - why don't you just use that one?

Blitz
  • 5,521
  • 3
  • 35
  • 53
  • This method has doc which says "optimizing for the case where the key is greater than all existing keys in the array." Does this mean it will put this object (key-value) at the end (last index)? When retrieving SparseArray.valueAt(size), will it give that object? – ahmadalibaloch Feb 17 '14 at 18:38
  • @ahmadalibaloch Why don't you try? There's also a put method. – Alexis C. Feb 17 '14 at 18:40
  • please everybody, I am not new to SparseArray. I know put shut and gut mutt. .append method dont insert at the end. I need to put an object at the last index of the array with a special key!!!! – ahmadalibaloch Feb 17 '14 at 18:57