31

I'm trying to sort an ArrayList in Java in Android app but I'm getting this weird exception.

Code:

eventsList.sort(new Comparator<Event>() {
        @Override
        public int compare(Event event, Event t1) {
            return event.getEventStartDate().compareTo(t1.getEventStartDate());
        }
    });

Exception:

java.lang.NoSuchMethodError: No interface method sort(Ljava/util/Comparator;)V in class Ljava/util/List; or its super classes (declaration of 'java.util.List' appears in /system/framework/core-libart.jar)

6 Answers 6

55

ArrayList#sort() was added in API level 24 and runtimes below API level 24 don't have that method. Looks like your compileSdkVersion is at 24 so you got the code to compile in the first place.

Use Collections.sort(list, comparator) instead.

1
  • 3
    mmmm, I used to use Collection.sort long back ago but today I just found this method in code completion in Android studio but likely it was a trap :). Thanks Commented Aug 15, 2016 at 8:06
30

Zxing?

If you get this error in the Zxing core lib in com.google.zxing.qrcode.detector.FinderPatternFinder.selectBestPatterns you can solve it by downgrading Zxing to 3.3.x (3.3.3 currently).

See https://github.com/zxing/zxing/issues/1170 for details.

0
16

In Zxing no need to downgrade version

just add following in App level gradle

android{
....
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

}

and

dependencies {
    ......
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
2
  • 1
    I found this same answer elsewhere but THIS is the right thing to do in 2021 so I upvoted.
    – gMale
    Commented Jun 6, 2021 at 23:11
  • 1
    this solution worked for me too as I didn't want to downgrade Commented Dec 5, 2021 at 8:35
6

What if you try

Collections.sort(eventsList, new Comparator...

As far as I know ArrayList doesn't have sort method.

0
4

List doesn't have its own sorting method, you'll need to call

Collections.sort() 

as the method on the list. If this returns a ClassCastError, that means the list has non-sortable items. I think this should fix it, but without full code, it's hard to check.

0
2

ArrayList.sort() method was added later that's why its not working. We can update java version (1.8) or we can use below method.

Collections.sort(eventList, new Comparator<Event>() {
        @Override
        public int compare(Event event, Event t1) {
            return event.getEventStartDate().compareTo(t1.getEventStartDate());
        }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.