androidsparse-array

indexOfValue(E) of SparseArrayCompat always return -1?


indexOfValue(E) method always return -1 while I am sure my E object exists in my SparseArray object, why? I have :

static final SparseArrayCompat<Long> LOCATION_SHARING_TIME = new SparseArrayCompat<Long>();
static {
    LOCATION_SHARING_TIME.put(0, LOCATION_SHARING_TIME_5s);
    LOCATION_SHARING_TIME.put(1, LOCATION_SHARING_TIME_1m);
    LOCATION_SHARING_TIME.put(2, LOCATION_SHARING_TIME_5m);
    LOCATION_SHARING_TIME.put(3, LOCATION_SHARING_TIME_30m);
    LOCATION_SHARING_TIME.put(4, LOCATION_SHARING_TIME_1h);
}

I cannot use SparseLongArray because it support API 18+ which my project support API 9 minimum.


Solution

  • Because it uses == instead of equal to determine the equality. See the implementation of the method:

    public int indexOfValue(E value) {  
      if (mGarbage) {
      gc();
      }
    
      for (int i = 0; i < mSize; i++)
      if (mValues[i] == value)
      return i;
    
      return -1;
    }
    

    One idea would be to extend the SparseArray and override the method replacing == with equal.

    public int indexOfValue(E value) {  
      if (mGarbage) {
      gc();
      }
    
      for (int i = 0; i < mSize; i++)
      if (mValues[i].equals(value))
      return i;
    
      return -1;
    }