如何比较两个整数?

发布于 2024-08-14 06:17:31 字数 505 浏览 2 评论 0原文

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

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

我可以想到这一点:

if (x == y) 

== 运算符仅比较引用,因此这只适用于较小的整数值。但也许自动装箱开始发挥作用了……?

if (x.equals(y)) 

这看起来是一项昂贵的操作。有没有这样计算的哈希码?

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

有点冗长...

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

爱要勇敢去追 2024-08-21 06:17:32

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

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

风吹过旳痕迹 2024-08-21 06:17:32
if (x.equals(y))

这看起来是一个昂贵的操作。有这样计算的哈希码吗?

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

JVM 很可能甚至会优化方法调用(内联方法内部发生的比较),因此此调用并不比在两个基元 int< 上使用 == 昂贵多少。 /代码>值。

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

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.

爺獨霸怡葒院 2024-08-21 06:17:32

小提示:从 Java 1.7 开始,Integer 类有一个静态的 compare(Integer, Integer) 方法,因此您只需调用 Integer.compare(x, y) 即可完成有了它(除了有关优化的问题)。

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

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.

陈年往事 2024-08-21 06:17:32

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

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

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

Integer a = 128;
Integer b = 128;

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

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

As far as performance goes, equals is actually more expensive because it ends up calling 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);
記柔刀 2024-08-21 06:17:32

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

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

}

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();
    }

}
━╋う一瞬間旳綻放 2024-08-21 06:17:32

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

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

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

如果代码调用得足够频繁,那么代码将被 JIT 内联,因此性能考虑应该不重要。

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

[已添加]

另外,需要进行 null 检查来保证相等测试是对称的 - x.equals(y) 应该与 y.equals(x) 相同,但如果其中之一为 null,则不同。

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

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

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

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

瞎闹 2024-08-21 06:17:32

Integer 类实现了 Comparable,因此您

x.compareTo(y) == 0

也可以尝试,如果您想要比较这些整数而不是相等,那么,x.compareTo

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

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

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

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

x.compareTo(y) == 0

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

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

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

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

爱你是孤单的心事 2024-08-21 06:17:32

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

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.

韵柒 2024-08-21 06:17:31

这就是 equals 方法的作用:

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

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

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

This is what the equals method does:

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文