[英]Sort integer array based on custom comparator
This is something simple but I'm obviously missing something.... 这很简单,但我显然缺少了一些东西。
I have a 2D array that contains integer representations of Color values that have been calculated from a BufferedImage object. 我有一个2D数组,其中包含从BufferedImage对象计算出的Color值的整数表示形式。 I also have a method to calculate the brightness value based on the integer values. 我也有一种基于整数值计算亮度值的方法。
I want to sort rows based on the brightness value. 我想根据亮度值对行进行排序。 However, I'm getting 但是,我越来越
sort(java.lang.Integer[], Comparator<? super Integer>) in Arrays cannot be applied
to (int[], IntComparator)
My comparator method: 我的比较器方法:
private class IntComparator implements Comparator<Integer>{
@Override
public int compare(Integer x, Integer y){
return (PhotoUtils.getBrightnessValue(x) <= PhotoUtils.getBrightnessValue(y)) ? x : y;
}
}
Inside my sortRow method, I have 在我的sortRow方法中,我有
public void sortRow(int row) {
Arrays.sort(this.buffer[row], new IntComparator());
}
What is the issue here? 这是什么问题? After all, I'm just calculating two integer values based on the input and returning either < 0 or > 0. 毕竟,我只是根据输入来计算两个整数值,并返回<0或> 0。
Make sure to declare the buffer
attribute as an Integer[]
, because you defined the comparator for the Integer
type, not for the int
type - and the sort()
method that receives a Comparator
will only work for arrays of object types, not for arrays of primitive types such as int
. 确保将buffer
属性声明为Integer[]
,因为您为Integer
类型而不是int
类型定义了比较器-接收Comparator
的sort()
方法仅适用于对象类型的数组,不适用于基本类型数组,例如int
。
Be aware that an int[]
can not be automatically converted to Integer[]
, it might be necessary to explicitly create a new Integer[]
and copy the int[]
elements into it: 请注意,不能将int[]
自动转换为Integer[]
,可能需要显式创建一个新的Integer[]
并将int[]
元素复制到其中:
int[] myIntArray = ...;
Integer[] myIntegerArray = new Integer[myIntArray.length];
for (int i = 0; i < myIntArray.length; i++)
myIntegerArray[i] = myIntArray[i]; // autoboxing takes care of conversion
The Arrays.sort(T[], Comparator)
is a generic method where both the first and second parameters use the type variable. Arrays.sort(T[], Comparator)
是一种通用方法,其中第一个和第二个参数都使用类型变量。 Since primitives can't be used as generic type arguments, ex. 由于原语不能用作泛型类型参数,因此。 Comparator<int>
, you cannot pass an int[]
as the first argument. Comparator<int>
,您不能将int[]
作为第一个参数传递。
You will need to pass an Integer[]
. 您将需要传递Integer[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.