Difference between put(...) and append(...) for a SparseArray?

Skyost picture Skyost · May 10, 2014 · Viewed 9.9k times · Source

I just want to know what is the difference between put(...) and append(...) for a SparseArray ?

From the official documentation :

  • append(...) : Puts a key/value pair into the array, optimizing for the case where the key is greater than all existing keys in the array.
  • put(...) : Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one.

But I just do not understand :s

Thanks for your help !

Answer

323go picture 323go · May 10, 2014

It appears to me that the documentation is pretty straightforward:

If you add sequential keys, such as 1, 2, 3, 5, 7, 11, 13..., use append().

If you add non-sequential keys, such as 100, 23, 45, 277, 42..., use put().

There's no reason you can't use put() in either scenario, but if you know the keys will be sequential -- for example, while loading data from storage -- then append() will give you a performance advantage.