Android - SortedList.indexOf() returns INVALID_POSITION

214 views Asked by At

I have come across a very strange behavior of SortedList. The method indexOf returns INVALID_POSITION even though in the debugger everything seems okay.

enter image description here

Method getWorkingDayItems of adapter workingDayAdapter returns SortedList.

As you can see, the 3rd element of the list is WorkingDay@4678 which is the same object as object workingDay. Yet the method indexOf returns -1.

Could you explain to me, why is this happening? Is there a known or not yet discovered but in the SortedList? Or is there another cause?

Thank you.

EDIT:

After removing overriding of equals method the problem persist.

enter image description here

2

There are 2 answers

2
Dominik 105 On

In normal lists in java the indexOf() method compares with the equals() method (I haven't found it for SortedList). Could it be the problem that you haven't overriden the equals() method in your WorkingDay class? I think if you pass a new instance of WorkingDay@4678 into your indexOf() method it would classify it with -1.

0
nlt On

In my case it's because I modified attribute localStatus of my object after adding items to the list, which is also being used in compare method, and SortedList uses binary search base on the output of compare method.

Here is my compare method

@Override
public int compare(SmsWrapper o1, SmsWrapper o2) {
    return o1.localStatus.ordinal() - o2.localStatus.ordinal();
}

Hope it help.