【发布时间】:2015-10-29 11:29:26
【问题描述】:
我在理解RecyclerViews SortedList时有些问题。
假设我有一个非常简单的类,只有一个非常简单的类保存数据:
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
+ "]";
}
}
我的理解是排序后的列表不会包含任何重复项。
但是当我有一个带有这样回调的 SortedList 时:
....
@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 但不同字符的项目时,我最终会出现重复。
sortedList.add(new Pojo(1, 'a'));
sortedList.add(new Pojo(1, 'b'));
我希望列表能够更新项目。相反,即使areItemsTheSame 返回了true,我现在也有多个项目。
【问题讨论】:
-
列表可以有重复项。尝试使用 hashMap。
-
据我了解不是"If the item already exists in the list and its sorting criteria is not changed, it is replaced with the existing Item."。我不需要 HashMap,因为我需要与 RecyclerView 的有效耦合。
-
为什么这个问题用 Java 标记?
-
@Paul Woitaschek 你设法解决了这个问题吗?
-
是的 @Ari 正在手动检查。见here
标签: java android android-recyclerview sortedlist