gpt4 book ai didi

java - Arrays.sort 引发编译时错误 'Anonymous class derived from Comparator..'

转载 作者:行者123 更新时间:2023-12-02 08:49:00 24 4
gpt4 key购买 nike

错误:

Anonymous class derived from Comparator must either be declared Abstract or implement abstract method compare(T,T).

我想根据 map 中的频率对数组进行排序。

HashMap<Integer,Integer> freq = new HashMap<>();
for(int a:arr)
{
freq.putIfAbsent(a,freq.getOrDefault(a,0)+1);
}
Arrays.sort(arr,new Comparator<>(){
public int compare(int a,int b)
{
if(freq.get(b)!=freq.get(a))
return freq.get(b)-freq.get(a);
else
return a-b;
}
});

我在这里缺少什么?

最佳答案

假设您有一个Integer[],例如

Integer[] arr = { 10, 2, 30, 4 };

您可以按如下方式进行:

Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (freq.get(b) != freq.get(a))
return Integer.compare(freq.get(b), freq.get(a));
else
return a.compareTo(b);
}
});

如果您有一个int [],例如

int[] arr = { 10, 2, 30, 4 };

将其转换为Integer[]

Integer[] arr1 = Arrays.stream(arr).boxed().toArray(Integer[]::new);

然后将arr1排序为

Arrays.sort(arr1, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (freq.get(b) != freq.get(a))
return Integer.compare(freq.get(b), freq.get(a));
else
return a.compareTo(b);
}
});

关于java - Arrays.sort 引发编译时错误 'Anonymous class derived from Comparator..',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com