-1

I have a game where I have an ArrayList of Mobs. Each mob has a position and I want to sort them by their Y value so the lowest mob is rendered last.

I am running LibGDX so the values range from -300 (bottom) to 300 (top).

This is the current setup:

Collections.sort(entities, new Comparator<Entity>() {
    @Override
    public int compare(Entity e1, Entity e2) {
        return String.valueOf(e1.position.y)
                     .compareTo(String.valueOf(e2.position.y));
    }

});

System.out.println("------------------------");
for (Entity e : entities) {
    System.out.println(entities.indexOf(e) + ": " + e.entityID);
    if (e != null) {
        e.draw(sb);
    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 2
    What is your actual question? – PM 77-1 Jul 25 '15 at 20:56
  • Agree with @PM77-1 that you ask no question, and add to it that you don't need to compare strings if you have doubles – Dici Jul 25 '15 at 20:57
  • If you make clear to the reader what question you are asking that will improve your chances of getting a useful reply. Reading [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) might give you some ideas. – Frank Boyne Jul 25 '15 at 21:06
  • I solved it thanks to @Pshemo, I converted them to strings because I didnt know how to compare doubles, as Pshemo pointed out strings sort didnt really work out as they sort in alphabetic order.. – Flash Records Jul 25 '15 at 21:13
  • Just a remark : comparing doubles is math... `Double.compare` is just a shortcut, but the logic of this method is completely trivial. If you think about it properly, you will see you should not have blocked on this – Dici Jul 25 '15 at 21:21

1 Answers1

3
String.valueOf(e1.position.y).compareTo(String.valueOf(e2.position.y))

will convert y values of your e1.position and e2.position to String, and then compareTo from string is using alphabetic order.

If y is numeric value like int and you want to sort it using numeric order you should use

Integer.compare(e1.position.y, e2.position.y)

BTW having public fields is bad practice which violates encapsulation. You should make them private and add getters and setters.

Also since Java 8 we can make our live easier and create comparator using lambdas like

Comparator.comparingInt((Entity e) -> e.position.y)

or

Comparator.<Entity>comparingInt(en -> en.position.y);
Pshemo
  • 122,468
  • 25
  • 185
  • 269