第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Android SparseArray 值比較

Android SparseArray 值比較

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

1 回答

?
慕勒3428872

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊

查看 的源代碼LongSparseArray,似乎該方法確實(shí)存在 - 但它是隱藏的(由于某種原因):

/**

* 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;

}

您可以看到所有這些代碼實(shí)際上所做的就是您在問(wèn)題中所說(shuō)的 - 循環(huán)遍歷所有值,直到找到正確的值,然后返回其索引。


Sparse***我不知道為什么它被排除在公共 API 之外,但在我看來(lái),這是反對(duì)使用任何東西的另一點(diǎn)。它們通常太基礎(chǔ),無(wú)法滿足我的要求。


查看完整回答
反對(duì) 回復(fù) 2023-10-12
  • 1 回答
  • 0 關(guān)注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)