Math.abs(Integer) not working, can't convert Integer to int

时间:2016-10-20 19:38:41

标签: java comparator

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?

1 个答案:

答案 0 :(得分:7)

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, so you can't chain .compareTo to it.

You are probably looking for something like

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

or (depending on version of your question)

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