Java Android Sparsarray值比较

Java Android Sparsarray值比较,java,android,android-sparsearray,Java,Android,Android Sparsearray,所以我写了一些非常简单的代码,发现了一个非常意外的行为。所有List和Map实现都使用节点的equals方法来比较它们。因此,如果您有一个字符串列表,并且尝试获取列表中字符串的索引,则不需要使用相同的对象。例如: List<String> list = new ArrayList<>(); list.add("test"); int index = list.indexOf("test"); System.out.println(index);//returns 0 因

所以我写了一些非常简单的代码,发现了一个非常意外的行为。所有
List
Map
实现都使用节点的
equals
方法来比较它们。因此,如果您有一个字符串列表,并且尝试获取列表中字符串的索引,则不需要使用相同的对象。例如:

List<String> list = new ArrayList<>();
list.add("test");
int index = list.indexOf("test");
System.out.println(index);//returns 0
因此,如果您有这样的简单代码:

LongSparseArray<String> localContacts = new LongSparseArray<>();
localContacts.put(2, "test");
int index = localContacts.indexOfValue("test");
System.out.println(index);
LongSparseArray localContacts=new LongSparseArray();
localContacts.put(2,“测试”);
int index=localContacts.indexOfValue(“测试”);
系统输出打印项次(索引);
这里的索引将返回-1(如果不知道如何比较值,这是非常意外的)


所以我想知道。。。为什么Android不使用
equals
?这是一种更方便、更可取的方法(从Java的角度来看)。现在,我必须循环查看
SparseArray
的所有值,并与自己进行比较,这会产生更多(不需要的)代码(或者使用
Map
,这会降低Android的性能)。

查看
LongSparseArray
的源代码,似乎这个方法确实存在,但它是隐藏的(出于某种原因):

/**
*返回一个索引,{@link#valueAt}将为其返回
*指定的键,如果没有键映射到
*指定的值。
*请注意,这是一个线性搜索,与按键查找不同,
*多个键可以映射到同一个值,这将
*只找到其中一个。
*还要注意,此方法使用{@code equals}而不是{@code indexOfValue}。
*@隐藏
*/
public int indexOfValueByValue(E值){
if(mGarbage){
gc();
}
对于(int i=0;i
您可以看到,这些代码所做的一切都是您在问题中所说的——循环遍历所有值,直到找到正确的值,并返回其索引


我不知道为什么它被排除在公共API之外,但在我看来,这是反对使用
Sparse***
任何东西的又一点。它们通常过于基本,无法满足我的需求。

看起来您可以使用
indexOfValueByValue
来使用相等比较(编辑:没关系,我发现这是因为某种原因隐藏的),感谢您的澄清。我只使用Sparsearray进行表演。
LongSparseArray<String> localContacts = new LongSparseArray<>();
localContacts.put(2, "test");
int index = localContacts.indexOfValue("test");
System.out.println(index);
/**
* 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;
}