Android:带重复项的SortedList [英] Android: SortedList with duplicates
问题描述
我在理解RecyclerView
s SortedList
时遇到了一些问题.
I have some problems understanding RecyclerView
s SortedList
.
让我们说我有一个非常简单的类,只有一个非常简单的类拥有数据:
Lets say I have a very simple class only having a very simple class holding data:
public class Pojo {
public final int id;
public final char aChar;
public Pojo(int id, char aChar) {
this.id = id;
this.aChar = aChar;
}
@Override
public String toString() {
return "Pojo[" + "id=" + id
+ ",aChar=" + aChar
+ "]";
}
}
我的理解是,排序后的列表不会包含任何重复项.
My understanding is that the sorted list won't contain any duplicates.
但是当我有一个带有这样的回调的SortedList时:
But when I have a SortedList with callbacks like this:
....
@Override
public boolean areContentsTheSame(Pojo oldItem, Pojo newItem) {
return oldItem.aChar == newItem.aChar;
}
@Override
public int compare(Pojo o1, Pojo o2) {
return Character.compare(o1.aChar, o2.aChar);
}
@Override
public boolean areItemsTheSame(Pojo item1, Pojo item2) {
return item1.id == item2.id;
}
当我添加多个具有相同ID但不同字符的项目时,我最终会重复.
I end up with duplicates when I add multiple items with the same id but different chars.
sortedList.add(new Pojo(1, 'a'));
sortedList.add(new Pojo(1, 'b'));
我希望列表会更新该项目.相反,即使areItemsTheSame
返回了true
,我现在还是有多个项目.
I would expect the list to update the item. Instead now I have multiple items even though areItemsTheSame
returned true
.
推荐答案
SortedList不会按ID保留任何映射(因为API中没有ID). 因此,当排序标准更改时(在您的情况下为a到b),SortedList无法找到现有元素.
SortedList does not keep any mapping by ids (because there are no ids in the API). So when the sorting criteria changes (a to b in your case), SortedList cannot find the existing element.
您可以自己保留ID映射,然后使用如下的add方法:
You can keep the id mapping yourself, then have your add method as follows:
void add(Item t) {
Item existing = idMap.get(t.id);
if (existing == null) {
sortedList.add(t);
} else {
sortedList.updateItemAt(sortedList.indexOf(existing), t);
}
idMap.put(t.id, t);
}
您还需要实现remove方法,以从idMap中删除项目.
You'll also need to implement a remove method to remove the item from the idMap.
这篇关于Android:带重复项的SortedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!