Java 如何比较两个整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1873832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:26:06  来源:igfitidea点击:

How do I compare two Integers?

javacomparisonobject-comparison

提问by Daniel Rikowski

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

我必须比较两个Integer对象(不是int)。比较它们的规范方法是什么?

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.

编辑:感谢您的回复。虽然我现在知道该怎么做,但事实分布在所有现有答案中(甚至是已删除的答案:)),我真的不知道该接受哪一个。所以我会接受最好的答案,它指的是所有三种比较可能性,或者至少是前两种。

采纳答案by Jeff

This is what the equals method does:

这就是 equals 方法的作用:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue()might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals()call anyway, though I don't know that for certain.

正如您所看到的,没有哈希码计算,但在那里进行了一些其他操作。虽然x.intValue() == y.intValue()可能会稍微快一些,但您正在那里进入微优化领域。另外编译器可能会优化equals()调用,尽管我不确定。

I generally would use the primitive int, but if I had to use Integer, I would stick with equals().

我通常会使用原语int,但如果必须使用Integer,我会坚持使用equals().

回答by svenningsson

Use the equalsmethod. Why are you so worried that it's expensive?

使用equals方法。你为什么这么担心它很贵?

回答by ZZ Coder

I would go with x.equals(y) because that's consistent way to check equality for all classes.

我会选择 x.equals(y) 因为这是检查所有类的相等性的一致方法。

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

就性能而言,equals 实际上更昂贵,因为它最终会调用 intValue()。

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

编辑:在大多数情况下,您应该避免自动装箱。它可能会变得非常混乱,尤其是作者不知道他在做什么。你可以试试这个代码,你会对结果感到惊讶;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

回答by Jesper

if (x.equals(y))

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

if (x.equals(y))

这看起来像是一项昂贵的操作。是否有任何以这种方式计算的哈希码?

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.

这不是一个昂贵的操作,也没有计算哈希码。Java 不会神奇地计算哈希码,equals(...)只是一个方法调用,与任何其他方法调用没有区别。

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

JVM 甚至很可能会优化方法调用(内联方法内部发生的比较),因此此调用并不比使用==两个原始int值昂贵多少。

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.

注意:不要过早地应用微优化;您像“这一定很慢”这样的假设很可能是错误的或无关紧要,因为代码不是性能瓶颈。

回答by mfx

"equals" is it. To be on the safe side, you should test for null-ness:

“等于”就是这样。为了安全起见,您应该测试空性:

x == y || (x != null && x.equals(y))

the x==y tests for null==null, which IMHO should be true.

x==y 测试 null==null,恕我直言应该是真的。

The code will be inlined by the JIT if it is called often enough, so performance considerations should not matter.

如果代码被足够频繁地调用,JIT 将内联该代码,因此性能考虑应该无关紧要。

Of course, avoiding "Integer" in favor of plain "int" is the best way, if you can.

当然,如果可以的话,避免使用“Integer”而使用“int”是最好的方法。

[Added]

[添加]

Also, the null-check is needed to guarantee that the equality test is symmetric -- x.equals(y) should by the same as y.equals(x), but isn't if one of them is null.

此外,需要空检查来保证相等测试是对称的——x.equals(y) 应该与 y.equals(x) 相同,但如果它们之一为空则不是。

回答by jhumble

The Integer class implements Comparable<Integer>, so you could try,

Integer 类实现了Comparable<Integer>,所以你可以尝试,

x.compareTo(y) == 0

also, if rather than equality, you are looking to compare these integers, then,

此外,如果您希望比较这些整数而不是相等,那么,

x.compareTo(y) < 0will tell you if x is less than y.

x.compareTo(y) < 0会告诉你 x 是否小于 y。

x.compareTo(y) > 0will tell you if x is greater than y.

x.compareTo(y) > 0会告诉你 x 是否大于 y。

Of course, it would be wise, in these examples, to ensure that x is non-null before making these calls.

当然,在这些示例中,明智的做法是在进行这些调用之前确保 x 非空。

回答by ktbiz

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

小注:从 Java 1.7 开始,Integer 类有一个静态compare(Integer, Integer)方法,所以你可以调用它Integer.compare(x, y)并完成它(关于优化的问题除外)。

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.

当然,该代码与 1.7 之前的 Java 版本不兼容,因此我建议x.compareTo(y)改用它,它与 1.2 兼容。

回答by user3468976

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:

比较整数并按值升序或降序打印其值。您所要做的就是实现 Comparator 接口并覆盖其比较方法并比较其值,如下所示:

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

}

回答by Abhinav

I just encountered this in my code and it took me a while to figure it out. I was doing an intersection of two sorted lists and was only getting small numbers in my output. I could get it to work by using (x - y == 0)instead of (x == y)during comparison.

我刚刚在我的代码中遇到了这个问题,我花了一段时间才弄明白。我正在做两个排序列表的交集,并且在我的输出中只得到很少的数字。我可以通过使用(x - y == 0)而不是(x == y)在比较期间使其工作。