简体   繁体   中英

Sorting objects in ArrayList

I'm trying to sort an ArrayList by two criterias: ascending in both row and col. I'm getting the following error:

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

Here's a simplified version of my code:

public class DenseBoard<T>{

    private ArrayList<RowColElem<T>> tempDiagList;

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

The first problem with your code comes from the extra parentheses in RowColElem::getRow() and RowColElem::getCol() . This is called a method reference ( section 15.13 of the JLS for the details).

Then, the real issue here is that the Java compiler cannot infer the correct type of the element in the lambda expression of comparingInt and it defaults to Object .

You have to specify the type of the expected element like this:

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

Another solution would be to use a local assignment:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM