0

I am trying to learning and switch to Java 8 from 7.
While I got problems when switch Arrays.sort, which gave my error: type is not applicable.
I knows there are some better ways to do the same task, but I would like to use the same function to have a better understanding.
Thanks in advance.

package src;

import java.util.Arrays;
import java.util.Comparator;

public class Java8Learning {
    public static void main(String[] args){
        Integer[] numbers = {4,5,3,2,6,1};
        -------java 7 ---------
        Arrays.sort(numbers, new Comparator<Integer>() {
            @Override
            public int compare(Integer firstNumber, Integer secondNumber){
                System.out.print("comparing :"+ firstNumber + " and " + secondNumber);
                return Integer.compare(firstNumber, secondNumber);
            }
        });
        -------java 8 ---------
        // it gave me error
        //The method sort(T[], Comparator<? super T>) in the type Arrays is not applicable for the arguments (Integer[], (<no type> firstNumber, <no type> secondNumber) -> {})
        Arrays.sort(numbers, (firstNumber, secondNumber) -> 
                                 {  System.out.print("comparing :"+ firstNumber + " and " + secondNumber);
                                     Integer.compare(firstNumber, secondNumber);
                                 });

    }
}

1 Answer 1

5

Missed a return before the Integer.compare

Arrays.sort(numbers, (firstNumber, secondNumber) -> 
                     {  System.out.print("comparing :"+ firstNumber + " and " + secondNumber);
                        return Integer.compare(firstNumber, secondNumber);
                     });
Sign up to request clarification or add additional context in comments.

1 Comment

With Java 13 this produces the following error for me: error: no suitable method found for sort(int[],(firstNumb...))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.