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)
Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64

6 Answers6

54

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • 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 – Hossam Ghareeb Aug 15 '16 at 08: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.

tobltobs
  • 2,782
  • 1
  • 27
  • 33
15

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'
}
code4rox
  • 941
  • 9
  • 34
  • 1
    I found [this same answer elsewhere](https://github.com/zxing/zxing/issues/1170#issuecomment-555860273) but THIS is the right thing to do in 2021 so I upvoted. – gMale Jun 06 '21 at 23:11
  • 1
    this solution worked for me too as I didn't want to downgrade – dubezOniner Dec 05 '21 at 08:35
6

What if you try

Collections.sort(eventsList, new Comparator...

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

mic4ael
  • 7,974
  • 3
  • 29
  • 42
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.

Matt
  • 135
  • 1
  • 10
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());
        }
});
Ravindra Kumar
  • 1,842
  • 14
  • 23