You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Comparator接口与Lambda表达式排序int数组遇编译错误求助

问题分析与解决方案

Hey, let's break down what's going on here and fix your code!

The core issue you're hitting is that the Arrays.sort overload that takes a Comparator only works with object arrays (like Integer[]), not primitive type arrays (like int[]). The compiler error spells this out clearly when it mentions equality constraints: int and upper bounds: Object — since Comparator operates on types that inherit from Object, the primitive int can't be used with this method.

Solution 1: Use Integer[] with Lambda + Comparator

If you specifically want to use a Lambda expression to define sorting logic, convert your primitive int[] to an Integer[] (boxed object array) first, sort it, then convert back if you need the primitive type:

import java.util.Arrays;

public class MyClass{
    public static void main(String args[]) {
        int[] arr = {5,3,7,8,1,4,6,9};
        
        // Convert primitive int array to Integer object array
        Integer[] integerArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
        
        // Sort using Lambda as Comparator (ascending order here)
        Arrays.sort(integerArr, (o1, o2) -> o1 - o2);
        
        // Convert back to int array if needed
        int[] sortedArr = Arrays.stream(integerArr).mapToInt(Integer::intValue).toArray();
        
        System.out.println(Arrays.toString(sortedArr));
    }
}

Solution 2: Use the default Arrays.sort(int[]) for simple ascending sort

If you just need a standard ascending sort, you don't need a Comparator at all! The default Arrays.sort(int[]) method is built specifically for primitive integer arrays and does exactly what you want:

import java.util.Arrays;
public class MyClass{
    public static void main(String args[]) {
        int[] arr = {5,3,7,8,1,4,6,9};
        Arrays.sort(arr); // Default ascending sort for primitive int array
        System.out.println(Arrays.toString(arr));
    }
}

Bonus: Custom sort (e.g., descending order) for primitive arrays

If you need a custom order like descending, you can use streams to handle boxing and sorting in one chain:

import java.util.Arrays;
public class MyClass{
    public static void main(String args[]) {
        int[] arr = {5,3,7,8,1,4,6,9};
        
        int[] sortedDescArr = Arrays.stream(arr)
                                    .boxed()
                                    .sorted((o1, o2) -> o2 - o1) // Descending order
                                    .mapToInt(Integer::intValue)
                                    .toArray();
                                    
        System.out.println(Arrays.toString(sortedDescArr));
    }
}

内容的提问来源于stack exchange,提问作者Harsh Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:40:54