Android:带有重复项的SortedList

Pau*_*hek 10 java android sortedlist android-recyclerview

我有一些理解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
                + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

我的理解是排序列表不包含任何重复项.

但是当我有一个带有这样的回调的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;
}
Run Code Online (Sandbox Code Playgroud)

当我添加具有相同ID但不同字符的多个项目时,我最终会重复.

sortedList.add(new Pojo(1, 'a'));
sortedList.add(new Pojo(1, 'b'));
Run Code Online (Sandbox Code Playgroud)

我希望列表更新该项目.相反,现在我有多个项目,即使areItemsTheSame返回true.

yig*_*git 9

SortedList不会按ID保留任何映射(因为API中没有id).因此,当排序条件发生变化时(在您的情况下为a到b),SortedList无法找到现有元素.

您可以自己保留id映射,然后按如下方式添加add方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

您还需要实现一个remove方法来从idMap中删除该项.


rob*_*cab 5

正如 Minhtdh 在他的回答中已经提到的,问题出在你的compare().

看,add()使用compare()您实现的查找现有对象的索引。因此,当您compare()返回 0 以外的值时,它会将对象添加到列表中。

在比较其内容之前,您需要检查项目是否相同。但是,如果您的内容可以相同,则需要进行二次比较。

这就是我compare()在您的情况下实施的方式:

@Override
public int compare(Pojo o1, Pojo o2) {
    int result;
    if (areItemsTheSame(o1, o2) {
        result = 0;
    } else {
        result = Character.compare(o1.aChar, o2.aChar);
        if (result == 0) {
            // TODO implement a secondary comparison 
        }
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)


Bor*_*ris -1

在 Java 中,不包含重复元素的集合是Set。常见的实现类是HashSetTreeSet。你假设 SortedList 这样做是错误的。