gpt4 book ai didi

java - .reversed() 无法在 blueJ 中编译

转载 作者:行者123 更新时间:2023-12-02 09:54:36 25 4
gpt4 key购买 nike

我有一种方法可以对我制作的类的表进行排序。除了方法末尾的“.reserved”阻止其编译之外,其他一切都很好。我该怎么做才能编译我的方法?

    public void sortTable(String division) {
List<Team> teamsForDivision = teams.get(division);
if (teamsForDivision == null) {
return;
}

Collections.sort(teamsForDivision, new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return o1.getPoints() - o2.getPoints();
}
}.reversed());
}

最佳答案

如果没有 BlueJ 报告的错误,就不可能正确回答,但是:

   Collections.sort(teamsForDivision, new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return o1.getPoints() - o2.getPoints();
}
}.reversed());

如果编译器指出存在语法错误,需要某些标记(例如“Unexpected token {, Expected )”),请尝试添加括号或创建变量:

使用括号:

   Collections.sort(teamsForDivision, (new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return o1.getPoints() - o2.getPoints();
}
}).reversed());

使用变量:

   Comparator<Team> pointComparator = new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return o1.getPoints() - o2.getPoints();
}
};
Collections.sort(teamsForDivision, pointComparator.reversed());

如果编译器警告您方法 reversed 不存在(这里最有可能出现这种情况),则意味着编译器使用低于 Java 8 的版本(该方法是在 Java 8 中添加的)扭转这个局面并不难:

Comparator<Team> pointComparator = new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return -(o1.getPoints() - o2.getPoints());
}
};

如果可能,您应该使用 Integer::compare 来代替:

Comparator<Team> pointComparator = new Comparator<Team>() {
@Override
public int compare(Team o1, Team o2) {
return -Integer.compare(o1.getPoints(), o2.getPoints());
}
}

最后,您还可以使用 lambda(如果支持 Java 8):

Comparator<Team> c = Comparator.comparingInt(Team::getPoints).reversed();

或者,您可能想要升级 BlueJ 版本:site说版本 4.1.2++ 支持 Java 8:

Can I run BlueJ with Java 9, 10, 11...?

The current version of BlueJ (4.1.2) requires Java 8. Most users (on either Windows or Mac platforms) should run BlueJ with the same JDK that it is bundled with – other versions have not been tested.

A future release of BlueJ will work with (and require) a later Java version. At this point in time we expect that BlueJ 4.2.0 will work with Java 11.

关于java - .reversed() 无法在 blueJ 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56091081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com