Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在ArrayList中排序对象_Java_Sorting_Arraylist_Java 8 - Fatal编程技术网

Java 在ArrayList中排序对象

Java 在ArrayList中排序对象,java,sorting,arraylist,java-8,Java,Sorting,Arraylist,Java 8,我试图按照两个标准对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 fo

我试图按照两个标准对
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
此行有多个标记
-令牌语法错误,请删除这些令牌
-类型的方法RowColElem()未定义
登革热
-类型的方法RowColElem()未定义
登革热
-令牌语法错误,请删除这些令牌
以下是我的代码的简化版本:

public class DenseBoard<T>{

    private ArrayList<RowColElem<T>> tempDiagList;

    public void foo() {
        Collections.sort(tempDiagList, Comparator.comparingInt(RowColElem::getRow())
                                                 .thenComparingInt(RowColElem::getCol()));
    }
}
公共类登月板{
私有数组列表;
公共图书馆{
Collections.sort(tempDiagList、Comparator.comparingInt(rowcolem::getRow())
.然后比较它(rowcolem::getCol());
}
}

代码的第一个问题来自
RowColElem::getRow()
RowColElem::getCol()
中的额外括号。这称为方法参考(有关详细信息,请参见JLS)

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

必须指定预期元素的类型,如下所示:

Collections.sort(list, Comparator.<RowColElem<T>> comparingInt(RowColElem::getRow)
                                                 .thenComparingInt(RowColElem::getCol));
Collections.sort(list,Comparator.comparingInt(rowcolem::getRow)
.然后比较(rowcolem::getCol));
另一种解决方案是使用本地分配:

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

删除
RowColElem::getRow()
RowColElem::getCol()
处的括号。仍然相同。我确实执行了
RowColElem::getRow
RowColElem::getCol
操作,但出现了错误<代码>此行有多个标记-RowColElem无法解析为变量-令牌上的语法错误,删除这些令牌-令牌上的语法错误,删除这些令牌-RowColElem无法解析为变量是否确实使用Java 8编译?你在使用IDE吗?然后试着把你的例子减少到最少。你的帖子中有太多的代码。我编辑了你的帖子,删除了所有不必要的代码,以便更容易看到真正的问题。我讨厌这样说,但它给了我同样的错误。它说RowColElem不能赋值给变量@TunakiDid你能复制第一段代码而不打字吗?我刚刚测试过,它可以工作。不需要在Java-8中使用
Collections.sort(list,comparator)
。只需调用
list.sort(comparator)