SparseArray vs HashMap

后端 未结 7 1691
-上瘾入骨i
-上瘾入骨i 2020-12-22 15:58

I can think of several reasons why HashMaps with integer keys are much better than SparseArrays:

  1. The Android documentation for a
7条回答
  •  半阙折子戏
    2020-12-22 16:42

    I came here just wanting an example of how to use SparseArray. This is a supplemental answer for that.

    Create a SparseArray

    SparseArray sparseArray = new SparseArray<>();
    

    A SparseArray maps integers to some Object, so you could replace String in the example above with any other Object. If you are mapping integers to integers then use SparseIntArray.

    Add or update items

    Use put (or append) to add elements to the array.

    sparseArray.put(10, "horse");
    sparseArray.put(3, "cow");
    sparseArray.put(1, "camel");
    sparseArray.put(99, "sheep");
    sparseArray.put(30, "goat");
    sparseArray.put(17, "pig");
    

    Note that the int keys do not need to be in order. This can also be used to change the value at a particular int key.

    Remove items

    Use remove (or delete) to remove elements from the array.

    sparseArray.remove(17); // "pig" removed
    

    The int parameter is the integer key.

    Lookup values for an int key

    Use get to get the value for some integer key.

    String someAnimal = sparseArray.get(99);  // "sheep"
    String anotherAnimal = sparseArray.get(200); // null
    

    You can use get(int key, E valueIfKeyNotFound) if you want to avoid getting null for missing keys.

    Iterate over the items

    You can use keyAt and valueAt some index to loop through the collection because the SparseArray maintains a separate index distinct from the int keys.

    int size = sparseArray.size();
    for (int i = 0; i < size; i++) {
    
        int key = sparseArray.keyAt(i);
        String value = sparseArray.valueAt(i);
    
        Log.i("TAG", "key: " + key + " value: " + value);
    }
    
    // key: 1 value: camel
    // key: 3 value: cow
    // key: 10 value: horse
    // key: 30 value: goat
    // key: 99 value: sheep
    

    Note that the keys are ordered in ascending value, not in the order that they were added.

提交回复
热议问题