int []的自定义比较器

时间:2016-03-02 05:49:21

标签: java

在Java中,我创建了一个以比较器作为参数的方法。我现在想用它来对int []进行排序。我收到一个错误,说基本类型int不能在比较器中使用。有办法解决这个问题吗?

int[] arr = {2,4,1,3};
sort (arr, new Comparator<int>() {
  @Override
  public int compare(int o1, int o2) {
    if (o1 > o2) return 1;
      if (o2 > o1) return -1;
        return 0;
      }
  });

2 个答案:

答案 0 :(得分:1)

没有使用比较器对int数组进行排序的标准库方法。您必须转换为Integer数组,然后使用Comparator<Integer>

Integer[] arr = {2,4,1,3}; 
Arrays.sort(arr, new Comparator<Integer>() { ... });

答案 1 :(得分:-1)

比较器仅使用Object类型变量。尝试在代码中使用Integer数据类型。

相关问题