3

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. 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

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.

1
  • You're conflating int[] and Integer[]. Note that you can autobox/auto-unbox from int to Integer and vice versa, but not from Integer[] to int[] and neither vice versa. Commented Dec 11, 2013 at 2:41

2 Answers 2

3

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.

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[] myIntArray = ...;
Integer[] myIntegerArray = new Integer[myIntArray.length];
for (int i = 0; i < myIntArray.length; i++)
    myIntegerArray[i] = myIntArray[i]; // autoboxing takes care of conversion
Sign up to request clarification or add additional context in comments.

Comments

1

The Arrays.sort(T[], Comparator) is a generic method where both the first and second parameters use the type variable. Since primitives can't be used as generic type arguments, ex. Comparator<int>, you cannot pass an int[] as the first argument.

You will need to pass an Integer[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.