1 回答

TA貢獻1848條經驗 獲得超6個贊
查看 的源代碼LongSparseArray
,似乎該方法確實存在 - 但它是隱藏的(由于某種原因):
/**
* Returns an index for which {@link #valueAt} would return the
* specified key, or a negative number if no keys map to the
* specified value.
* <p>Beware that this is a linear search, unlike lookups by key,
* and that multiple keys can map to the same value and this will
* find only one of them.
* <p>Note also that this method uses {@code equals} unlike {@code indexOfValue}.
* @hide
*/
public int indexOfValueByValue(E value) {
if (mGarbage) {
gc();
}
for (int i = 0; i < mSize; i++) {
if (value == null) {
if (mValues[i] == null) {
return i;
}
} else {
if (value.equals(mValues[i])) {
return i;
}
}
}
return -1;
}
您可以看到所有這些代碼實際上所做的就是您在問題中所說的 - 循環遍歷所有值,直到找到正確的值,然后返回其索引。
Sparse***我不知道為什么它被排除在公共 API 之外,但在我看來,這是反對使用任何東西的另一點。它們通常太基礎,無法滿足我的要求。
添加回答
舉報