user4833678
user4833678

Reputation:

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

Upvotes: 2

Views: 110

Answers (1)

Tunaki
Tunaki

Reputation: 137064

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

Upvotes: 3

Related Questions