Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects of a class

Tags:

java

I'm working on a Java project that asks me to implement the function obtainRanking() : void with the following description:

Sort the players list by using the class method sort (List) from the Collections class, a method to sort the objects of a collection. For that, the object's class (Player in our case), should implement the interface "Comparable" and its method compareTo.

So far, this is how I implemented the interface Comparable:

package modeloqytetet;

public interface Comparable {
    public int compareTo(Object otroJugador);
}

Inside class Player this is how I implemented the said method:

@Override
    public int compareTo(Object otherJugador) {
        int otherCapital = ((Player) otherJugador).getCapital();

        return otherCapital-getCapital();
    }

Now, the method obtainRanking() : void should be implemented in other class and I don't know how to do it. I've been trying to figure out by looking some examples around the internet but nothing seems to work.

Any help would be appreciated.

like image 819
d3vcho Avatar asked Mar 22 '26 12:03

d3vcho


1 Answers

The instructions is telling you to implement java.lang.Comparable<T>, not your own Comparable interface.

You should do this:

class Player implements Comparable<Player> {
    @Override
    public int compareTo(Player other) {
        return Integer.compare(this.getCapital(), other.getCapital());
    }

    ...
}

For why you should not simply subtract one integer from another to compare them, see here.

Then, you can implement obtainRankings like this:

// this name is quite bad. I would call it sortPlayersCapitalInPlace or something like that
public void obtainRankings(List<Player> players) {
    Collections.sort(players);
}
like image 159
Sweeper Avatar answered Mar 24 '26 04:03

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!