这里为啥报红线?该如何修改?

这里为啥报红线?该如何修改?

img


完整代码:

package test;

import java.util.Arrays;

public class test {
    public static void main(String[] args) {
        int[] ans = {3, 4, 5, 7, 8, 10};
        Arrays.sort(ans, new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                int i1 = (Integer) o1;//拆箱
                int i2 = (Integer) o2;
                return i1 - i2;
            }
        }));
    }

    public void bubbleSort(int[] ans, Comparator c) {
        for (int i = 0; i < ans.length - 1; i++) {
            for (int j = 0; j < ans.length - i - 1; j++) {
                if (c.compare(ans[j], ans[j + 1]) > 0) {
                    int temp = ans[j];
                    ans[j] = ans[j + 1];
                    ans[j + 1] = temp;
                }
            }
        }
    }
    public static interface Comparator {
        public int compare (Object o1, Object o2) ;
    }
}

你自己定义了一个 Comparator 接口,这肯定是不行的, Arrays.sort 里面引入的是 java.util.Comparator

        Integer[] ans = {3, 4, 5, 7, 8, 10};
        Arrays.sort(ans, new Comparator<Integer>(){
            @Override
            public int compare(Integer i1, Integer i2) {
                return i1 - i2;
            }
        });

一个泛型的问题,需要将Comparator改
为Comparator,
表示这个接口是一个针对整数类型的比较器。另外,在实现该接口的匿名类中,也需要将括号内的Object改为Integer,以表明要比较的是整数类型。

package test;

import java.util.Arrays;

public class test {

    public static void main(String[] args) {
        int[] ans = {3, 4, 5, 7, 8, 10};
        Arrays.sort(ans, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
    }

    public void bubbleSort(int[] ans, Comparator<Integer> c) {
        for (int i = 0; i < ans.length - 1; i++) {
            for (int j = 0; j < ans.length - i - 1; j++) {
                if (c.compare(ans[j], ans[j + 1]) > 0) {
                    int temp = ans[j];
                    ans[j] = ans[j + 1];
                    ans[j + 1] = temp;
                }
            }
        }
    }

    public static interface Comparator<T> {
        public int compare(T o1, T o2);
    }
}