亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Android SparseArray 值比較

Android SparseArray 值比較

智慧大石 2023-10-12 17:07:14
所以我正在編寫一些非常簡單的代碼,并發現了一個非常意外的行為。所有實現List都Map使用equals節點的方法來比較它們。因此,如果您有一個字符串列表,并且您想嘗試獲取列表中字符串的索引,則不需要使用相同的對象。例子:List<String> list = new ArrayList<>();list.add("test");int index = list.indexOf("test");System.out.println(index);//returns 0我注意到 Android 的所有 SparseArray 類都使用==而不是equals比較節點。示例方法(LongSparseArray.java):public int indexOfValue(E value) {    if (mGarbage) {    gc();    }for (int i = 0; i < mSize; i++) {    if (mValues[i] == value) {        return i;        }    }        return -1;}因此,如果您有這樣的簡單代碼:LongSparseArray<String> localContacts = new LongSparseArray<>();localContacts.put(2, "test");int index = localContacts.indexOfValue("test");System.out.println(index);這里的索引將返回 -1(如果您不知道如何比較該值,這是非常意外的)。所以我想知道...為什么Android不使用equals?這是更方便和更受歡迎的方式(從 Java 的角度來看)?,F在我必須循環遍歷 a 的所有值SparseArray并自己比較它們,這會導致更多(不需要的)代碼(或者使用 a 會Map導致 Android 性能降低)。
查看完整描述

1 回答

?
慕勒3428872

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 之外,但在我看來,這是反對使用任何東西的另一點。它們通常太基礎,無法滿足我的要求。


查看完整回答
反對 回復 2023-10-12
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號