-7

I have a list of objects, each object has a method that returns distance from player to said object like that

object.distance(player)

now i need to sort that list from loqwest distance to furthest

Jirka Kastan
  • 99
  • 1
  • 9
  • 1
    What have you tried? What specifically do you need help with? – Carcigenicate Nov 17 '18 at 17:48
  • What is your take on this. How would you solve it? – triplem Nov 17 '18 at 17:48
  • I tried iterating through the list and storing to an array distance for each object with key then sorting and returning the first, but is there better way of doing this? – Jirka Kastan Nov 17 '18 at 17:52
  • I think a bit more code would be helpful here. In essence, [you sort using a comparator](https://stackoverflow.com/questions/41141672/java-sorting-in-descending-order-using-comparator), but if there is a `List` of some object, I'm not sure where the `player` is coming from. – KevinO Nov 17 '18 at 17:54

1 Answers1

0

You can use interface java.lang.Comparable in java

Example (pseudo code) assuming object.distance(player) returns an Integer value

class Distance implements Comparable<Distance>{
  /**
    * Compare a given Distance with this object.
    */
    public int compareTo(Distance o) {
        return this.distance(player).compareTo(o.distance(o.player));
    }
}

now you can sort your list like

Collections.sort(YourListOfDistance)

here some reference

When should a class be Comparable and/or Comparator?

Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37