-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

4
  • 1
    What have you tried? What specifically do you need help with? Commented Nov 17, 2018 at 17:48
  • What is your take on this. How would you solve it? Commented Nov 17, 2018 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? Commented Nov 17, 2018 at 17:52
  • I think a bit more code would be helpful here. In essence, you sort using a comparator, but if there is a List of some object, I'm not sure where the player is coming from. Commented Nov 17, 2018 at 17:54

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.