How do I compare two Integers? [duplicate]

2019-01-13 07:47发布

This question already has an answer here:

I have to compare two Integer objects (not int). What is the canonical way to compare them?

Integer x = ...
Integer y = ...

I can think of this:

if (x == y) 

The == operator only compares references, so this will only work for lower integer values. But perhaps auto-boxing kicks in...?

if (x.equals(y)) 

This looks like an expensive operation. Are there any hash codes calculated this way?

if (x.intValue() == y.intValue())

A little bit verbose...

EDIT: Thank you for your responses. Although I know what to do now, the facts are distributed on all of the existing answers (even the deleted ones :)) and I don't really know, which one to accept. So I'll accept the best answer, which refers to all three comparison possibilities, or at least the first two.

9条回答
孤傲高冷的网名
2楼-- · 2019-01-13 08:27

Compare integer and print its value in value ascending or descending order. All you have to do is implements Comparator interface and override its compare method and compare its value as below:

@Override
public int compare(Integer o1, Integer o2) {
    if (ascending) {
        return o1.intValue() - o2.intValue();
    } else {
        return o2.intValue() - o1.intValue();
    }

}
查看更多
Fickle 薄情
3楼-- · 2019-01-13 08:31
if (x.equals(y))

This looks like an expensive operation. Are there any hash codes calculated this way?

It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...) is just a method call, not different from any other method call.

The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using == on two primitive int values.

Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.

查看更多
SAY GOODBYE
4楼-- · 2019-01-13 08:32

Minor note: since Java 1.7 the Integer class has a static compare(Integer, Integer) method, so you can just call Integer.compare(x, y) and be done with it (questions about optimization aside).

Of course that code is incompatible with versions of Java before 1.7, so I would recommend using x.compareTo(y) instead, which is compatible back to 1.2.

查看更多
登录 后发表回答