0

I have a LongSparseArray variable, in which the objects stored implement the interface Comparable. Is there a easy way to sort them, without do it "manually"? I tried Collections.sort(myLongSparseArray), but it does not implements the List interface.

Another way could be convert it to a List, but still I have not found any method to do that.

Daniele Vitali
  • 3,848
  • 8
  • 48
  • 71

1 Answers1

0

SparseArray, or LongSparseArray, should be considered as an efficient hash table when the keys are integers or longs. As such, it is not the best class to use if ordering is important to you.

Usually, when using hash-table type data structures, then uniqueness of values & efficiency of get / set are important.

If this is the case, perhaps you should look into using LinkedHashSet? It provides a way of holding unique items (based on their hashCode & equals functions), but also preserves the order of items, and has high efficiency of get / set.

If sorting is important, then you could extract the value list from the LinkedHashSet, then place it in a List, and use Collections.Sort() on it.

Gil Moshayof
  • 16,633
  • 4
  • 47
  • 58
  • Thank you for your answer. The problem is that I need an HashMap in order to efficiently get access to a value given its key. But I also need to order them so, now, I'm converting the HashMap into an ArrayList and then sort it. I thought LongSparseArray was able to behave both as HashMap and ArrayList. – Daniele Vitali Jul 03 '14 at 11:45