I get the below exception on this line when I run my program in android.
private PriorityQueue<Creature> turnqueue = new PriorityQueue<Creature>(new TurnComparator());
FATAL EXCEPTION: GLThread 18092
Process: com.buckriderstudio.clonequest, PID: 10171
java.lang.NoSuchMethodError: No direct method <init>(Ljava/util/Comparator;)V in class Ljava/util/PriorityQueue; or its super classes (declaration of 'java.util.PriorityQueue' appears in /system/framework/core-libart.jar)
This is how my comparator looks:
public class TurnComparator implements Comparator<Creature> {
@Override
public int compare(Creature c1, Creature c2) {
if (c1.getNextMove() < c2.getNextMove()) return -1;
if (c1.getNextMove() > c2.getNextMove()) return 1;
else return 0;
}
}
It seems it is some kind of compatibility issue but I'm not sure how to fix this. Does Android not support a Comparator
at all or do I need to change it a bit to fix this? What would be a good compatible substitute for comparing a PriorityQueue
?
If you take a look at the java documentation, you will see that there is no such constructor for priority queue:
https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
You need to also specifify the initial capacity ie
private PriorityQueue<Creature> turnqueue = new PriorityQueue<Creature>(5, new TurnComparator());
Update: It's worth noting that this DOES work in Java 8 - they have added an extra constructor. https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html
ArrayList.sort() method was added later in API level 24 that's why its not working. There may be two solution either you can update java version or you can use below method.
Collections.sort(yourList, new Comparator<Creature>() {
@Override
public int compare(Creature c1, Creature c2) {
if (c1.getNextMove() < c2.getNextMove()) return -1;
if (c1.getNextMove() > c2.getNextMove()) return 1;
else return 0;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.