gpt4 book ai didi

android - SimpleArrayMap 和 ArrayMap 是为了保持顺序吗?

转载 作者:行者123 更新时间:2023-11-29 19:29:24 28 4
gpt4 key购买 nike

我知道 SimpleArrayMap ArrayMap 类旨在更有效地(对于少量项目)替换 HashMap . HashMap没有可预测的迭代顺序(与 LinkedHashMap 不同),但我注意到 SimpleArrayMap 中的一些方法和 ArrayMap让我相信它们可能的类(class)。

类似 keyAt(int index) 的方法, valueAt(int index) removeAt(int index) 似乎表明 SimpleArrayMapArrayMap以可预测的方式存储他们的元素。这些方法也将使访问这些项目变得非常方便,所以我添加了一个 ArrayMapFragmentPagerAdapter保存每个页面的标题和 fragment :

public class TabPagerAdapter extends FragmentPagerAdapter {

private final ArrayMap<CharSequence, Fragment> mData = new ArrayMap();

public TabPagerAdapter(FragmentManager manager) {
super(manager);
}

public void addPage(CharSequence title, Fragment fragment) {
mData.put(title, fragment);
}

@Override
public CharSequence getPageTitle(int position) {
return mData.keyAt(position);
}

@Override
public Fragment getItem(int position) {
return mData.valueAt(position);
}

@Override
public int getCount() {
return mData.size();
}

}

虽然我在实践中注意到 getPageTitle() 返回的项目和 getItem()并不总是按照我将它们添加到 ArrayMap 的顺序.但是,如果这些项目的索引不可预测,为什么这些类会有按索引返回键和值的方法(而不是仅仅使用 Map#get(Object key) 方法)?

SimpleArrayMapArrayMap意味着保留顺序?难道我做错了什么?或者,如果没有,为什么它们会包含上述方法?

最佳答案

在查看 SimpleArrayMap 实现后,它似乎在调用 put、putAll 或 remove 方法时动态增长和收缩。那时你的索引可能会改变。如果您调用 notifyDataSetChanged()在你打电话后,你可能会有更好的时间。现在这只是我对你的代码的推理,所以不能保证。 :)

更仔细地看,indexOf 方法需要在项目的假定索引周围搜索,因为在缩小 map 时,指向索引的键哈希的内部数组似乎没有更新。所以索引显然可以改变。

int index = ContainerHelpers.binarySearch(mHashes, N, hash);

// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index;
}

// If the key at the returned index matches, that's what we want.
if (key.equals(mArray[index<<1])) {
return index;
}

// Search for a matching key after the index.
int end;
for (end = index + 1; end < N && mHashes[end] == hash; end++) {
if (key.equals(mArray[end << 1])) return end;
}

// Search for a matching key before the index.
for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {
if (key.equals(mArray[i << 1])) return i;
}

// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return ~end;

索引方法可能存在于您知道 map 没有发生任何修改的情况下。

更新:为了让它做你想做的事,你需要实现public long getItemId(int position) 同样,因为您的位置没有为您提供稳定的项目 ID。

我想说的是,如果您希望底层 map 发生变化,那么使用索引方法可能不是您的最佳选择,因为必须更新缓存的索引。

关于android - SimpleArrayMap 和 ArrayMap 是为了保持顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40425019/

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