Android: SortedList with duplicates

后端 未结 6 915
栀梦
栀梦 2021-02-19 21:58

I have some problems understanding RecyclerViews SortedList.

Lets say I have a very simple class only having a very simple class holding data:<

6条回答
  •  爱一瞬间的悲伤
    2021-02-19 22:16

    As Minhtdh already mentioned in his answer, the problem lies within your compare().

    See, add() looks up the existing object's index by using the compare() you implement. Therefore when your compare() returns something other than 0 it adds the object to the list.

    You would need to check if the items are the same before comparing it's contents. However, if your content can be the same you would need a secondary comparison.

    This is how I would implement the compare() in your case:

    @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;
    }
    

提交回复
热议问题