【问题标题】:Sorting objects in ArrayList对 ArrayList 中的对象进行排序
【发布时间】:2015-12-17 09:48:13
【问题描述】:

我试图通过两个标准对ArrayList 进行排序:在行和列中都升序。我收到以下错误:

Multiple markers at this line
    - Syntax error on tokens, delete these tokens
    - The method RowColElem() is undefined for the type 
     DenseBoard<T>
    - The method RowColElem() is undefined for the type 
     DenseBoard<T>
    - Syntax error on tokens, delete these tokens

这是我的代码的简化版本:

public class DenseBoard<T>{

    private ArrayList<RowColElem<T>> tempDiagList;

    public void foo() {
        Collections.sort(tempDiagList, Comparator.comparingInt(RowColElem::getRow())
                                                 .thenComparingInt(RowColElem::getCol()));
    }
}

【问题讨论】:

  • 去掉RowColElem::getRow()RowColElem::getCol()的括号。
  • 还是一样。我做了RowColElem::getRowRowColElem::getCol 但仍然出现错误。 Multiple markers at this line - RowColElem cannot be resolved to a variable - Syntax error on tokens, delete these tokens - Syntax error on tokens, delete these tokens - RowColElem cannot be resolved to a variable
  • 您确定使用 Java 8 进行编译吗?你在使用 IDE 吗?
  • 然后尝试将您的示例减少到最小的示例。您的帖子中的代码过多。
  • 我编辑了您的帖子以删除所有不必要的代码,以便更容易看到真正的问题。

标签: java sorting arraylist java-8


【解决方案1】:

您的代码的第一个问题来自RowColElem::getRow()RowColElem::getCol() 中的额外括号。这称为方法引用(详情请参阅 JLS 的section 15.13)。

那么,这里真正的问题是 Java 编译器无法推断出 comparingInt 的 lambda 表达式中元素的正确类型,它默认为 Object

您必须像这样指定预期元素的类型:

Collections.sort(list, Comparator.<RowColElem<T>> comparingInt(RowColElem::getRow)
                                                 .thenComparingInt(RowColElem::getCol));

另一种解决方案是使用本地分配:

Comparator<RowColElem<T>> comparator = Comparator.comparingInt(RowColElem::getRow);
List<RowColElem<T>> list = new ArrayList<>();
Collections.sort(list, comparator.thenComparingInt(RowColElem::getCol));

【讨论】:

  • 我讨厌这样说,但它给了我同样的错误。它说 RowColElem 不能分配给变量,@Tunaki
  • 你复制第一个sn-p的代码没有错字吗?我刚刚测试过,它可以工作。
  • 在 Java-8 中无需使用 Collections.sort(list, comparator)。只需致电list.sort(comparator)
猜你喜欢
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2012-02-22
  • 2017-12-12
  • 2013-01-06
相关资源
最近更新 更多