gpt4 book ai didi

java - Android SparseArray 值比较

转载 作者:行者123 更新时间:2023-12-02 19:49:32 29 4
gpt4 key购买 nike

所以我正在编写一些非常简单的代码,并发现了非常意外的行为。所有 ListMap 实现都使用节点的 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 的角度来看)。现在我必须循环遍历 SparseArray 的所有值并自己进行比较,这会导致更多(不需要的)代码(或者使用 Map 会导致性能降低)安卓)。

最佳答案

查看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;
}

您可以看到所有这些代码实际上所做的就是您在问题中所说的 - 循环遍历所有值,直到找到正确的值,然后返回其索引。

我不知道为什么这已被排除在公共(public) API 之外,但在我看来,这又是反对使用 Sparse*** 任何内容的另一点。它们通常太基础,无法满足我的要求。

关于java - Android SparseArray 值比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300113/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com