How to iterate through SparseArray?

后端 未结 10 1745
野的像风
野的像风 2020-11-30 18:16

Is there a way to iterate over Java SparseArray (for Android) ? I used sparsearray to easily get values by index. I could not find one.

10条回答
  •  长情又很酷
    2020-11-30 18:38

    The accepted answer has some holes in it. The beauty of the SparseArray is that it allows gaps in the indeces. So, we could have two maps like so, in a SparseArray...

    (0,true)
    (250,true)
    

    Notice the size here would be 2. If we iterate over size, we will only get values for the values mapped to index 0 and index 1. So the mapping with a key of 250 is not accessed.

    for(int i = 0; i < sparseArray.size(); i++) {
       int key = sparseArray.keyAt(i);
       // get the object by the key.
       Object obj = sparseArray.get(key);
    }
    

    The best way to do this is to iterate over the size of your data set, then check those indeces with a get() on the array. Here is an example with an adapter where I am allowing batch delete of items.

    for (int index = 0; index < mAdapter.getItemCount(); index++) {
         if (toDelete.get(index) == true) {
            long idOfItemToDelete = (allItems.get(index).getId());
            mDbManager.markItemForDeletion(idOfItemToDelete);
            }
        }
    

    I think ideally the SparseArray family would have a getKeys() method, but alas it does not.

提交回复
热议问题