简体   繁体   中英

Problems with Collections.Sort() in Java

i already googled the problem but it seems that everyone has an other issue. Maybe someone can help me:

I always get this Error Message at some (random) point:

Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeLo(ComparableTimSort.java:740)
at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:477)
at java.util.ComparableTimSort.mergeCollapse(ComparableTimSort.java:402)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:209)
at java.util.Arrays.sort(Arrays.java:1312)
at java.util.Arrays.sort(Arrays.java:1506)
at java.util.ArrayList.sort(ArrayList.java:1454)
at java.util.Collections.sort(Collections.java:141)
at com.mygdx.game.GdxGame.render(GdxGame.java:187)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

and this is my compare method:

@Override
public int compareTo(Entity entity) {
    return (int)(entity.y - y);
}

thank you in advance!

Most likely you are getting an overflow/underflow resulting in a comparison which is not always as intended. ie if the difference between entity.y and y >= 2 31 it will overflow and have the opposite sign to what it should. I suggest you use

public int compareTo(Entity entity) {
    return Long.compare(entity.y, y);
}

or

public int compareTo(Entity entity) {
    return entity.y > y ? +1 : entity.y < y ? -1 : 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM