然而,试图对对象列表进行排序:java:int不能被取消引用

所以我有一个对象 TeamStats。

我希望能够对 teamStats 列表进行排序,gamesWon但是,当我尝试实现如下所示的 compareTo 方法时,我收到错误消息:java: int cannot be dereferenced

我不知道为什么会这样,因为我正在关注这个 ArrayList 排序教程,他们似乎没有同样的问题。

为什么我会收到此错误以及如何避免它?

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());
    }
}

回答

intjava 中的 s 是本机类型,而不是对象。因此,他们没有方法(在您的示例中compareTo

调用o2.getGamesWon()返回一个本地int而不是Integer(包装器类型)。

将代码更改为以下内容,它应该可以工作

    @Override
    public int compare(TeamStats o1, TeamStats o2) {
        // Thanks to Hovercraft Full Of Eels!
        return Integer.compare(o1.getGamesWon(), o2.getGamesWon()); 
    }

  • The canonical solution is not to use subtraction but rather to use `Integer.compare(...)` which handles edge cases better
  • As always - of course there is a guy who beats me to the answer by 5 sec. Good job, man! 😀

回答

当然@Augusto 的答案是完全正确的。

这是创建Comparator<TeamStats>Comparator直接实现接口的另一种可能性:

Comparator<TeamStats> comparator = Comparator.comparing(TeamStats::getGamesWon);


以上是然而,试图对对象列表进行排序:java:int不能被取消引用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>