Emilia Clarke - 2 months ago 12

Java Question

I'm implementing a Comparator that sorts based on absolute value. All I (think) I need is this single line of code:

`public int compare(Integer int1, Integer int2) {`

return Math.abs(int1).compareTo(Math.abs(int2));

}

The error:

`'no suitable method found for abs(Integer)`

I thought that Java unboxes the Integer object to int?

I tried pulling the int value from the two Integer objects using .intValue(), but that didn't work either. What am I doing wrong?

Answer

`Math#abs(int)`

will indeed unbox `Integer`

to `int`

if you pass it as argument, but then it will return result as `int`

which is primitive type, so it doesn't have *any* methods.

You are probably looking for something like

```
Integer.compare(Math.abs(int1), int2);
```

or

```
Integer.compare(Math.abs(int1), Math.abs(int2));
```