我正在尝试学习并从7开始转换到Java 8 当我在切换Arrays.sort时出现问题,这给出了我的错误:type不适用 我知道有一些更好的方法可以完成相同的任务,但我想使用相同的功能来更好地理解 提前谢谢。
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);
});
}
}
答案 0 :(得分:3)
错过了Integer.compare
之前的回复Arrays.sort(numbers, (firstNumber, secondNumber) ->
{ System.out.print("comparing :"+ firstNumber + " and " + secondNumber);
return Integer.compare(firstNumber, secondNumber);
});