0

So I have an object TeamStats.

I would like to be able to sort a teamStats list by gamesWon however, when I try to implement the compareTo method as shown below, I am getting the error message: java: int cannot be dereferenced.

I cannot figure out why that is, as I am following this ArrayList sorting tutorial and they do not seem to have the same problem.

Why am I getting this error and how do I avoid it?

package sample;

import java.util.Comparator;

public class TeamStats implements Comparator<TeamStats>  {

    int teamID;
    int gamesPlayed;
    int gamesWon;
    int setsWon;

    public TeamStats(int teamID, int gamesPlayed, int gamesWon, int setsWon) {
        this.teamID = teamID;
        this.gamesPlayed = gamesPlayed;
        this.gamesWon = gamesWon;
        this.setsWon = setsWon;
    }

    public int getTeamID() {
        return teamID;
    }

    public void setTeamID(int teamID) {
        this.teamID = teamID;
    }

    public int getGamesPlayed() {
        return gamesPlayed;
    }

    public void setGamesPlayed(int gamesPlayed) {
        this.gamesPlayed = gamesPlayed;
    }

    public int getGamesWon() {
        return gamesWon;
    }

    public void setGamesWon(int gamesWon) {
        this.gamesWon = gamesWon;
    }

    public int getSetsWon() {
        return setsWon;
    }

    public void setSetsWon(int setsWon) {
        this.setsWon = setsWon;
    }


    @Override
    public int compare(TeamStats o1, TeamStats o2) {
        return o2.getGamesWon().compareTo(o1.getGamesWon());
    }
}

Josh Brett
  • 77
  • 3
  • 18

2 Answers2

7

ints in java are native types, not objects. As such they don't have methods (in your example compareTo)

The call o2.getGamesWon() returns a native int not an Integer (the wrapper type).

Change the code to the following and it should work

    @Override
    public int compare(TeamStats o1, TeamStats o2) {
        // Thanks to Hovercraft Full Of Eels!
        return Integer.compare(o1.getGamesWon(), o2.getGamesWon()); 
    }
Augusto
  • 28,839
  • 5
  • 58
  • 88
4

Of course the answer of @Augusto is completely correct.

Here is just another possibility to create a Comparator<TeamStats> without implementing the Comparator interface directly:

Comparator<TeamStats> comparator = Comparator.comparing(TeamStats::getGamesWon);
alex87
  • 449
  • 3
  • 8