This question already has an answer here:
这个问题在这里已有答案:
- How to properly compare two Integers in Java? 8 answers
如何正确比较Java中的两个整数? 8个答案
I have to compare two Integer
objects (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.
编辑:谢谢你的回复。虽然我知道现在要做什么,事实是分布在所有现有的答案(甚至是已删除的答案:))我并不知道,接受哪一个。所以我会接受最好的答案,它指的是所有三种比较可能性,或者至少是前两种。
9 个解决方案
#1
32
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()。
#2
26
Use the equals
method. Why are you so worried that it's expensive?
使用equals方法。你为什么这么担心它的价格昂贵?
#3
12
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.
这不是一项昂贵的操作,也没有计算哈希码。 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 int
values.
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.
注意:不要过早地应用微优化;你的假设如“这必须很慢”很可能是错误的或无关紧要,因为代码不是性能瓶颈。
#4
8
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);
#5
8
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类有一个静态比较(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兼容。
#6
2
"equals" is it. To be on the safe side, you should test for null-ness:
“等于”就是这样。为了安全起见,您应该测试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经常被调用,那么代码将由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)相同,但如果其中一个为null,则不需要。
#7
2
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接口并覆盖其compare方法并比较其值,如下所示:
@Override
public int compare(Integer o1, Integer o2) {
if (ascending) {
return o1.intValue() - o2.intValue();
} else {
return o2.intValue() - o1.intValue();
}
}
#8
1
The Integer class implements Comparable<Integer>
, so you could try,
Integer类实现了Comparable
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将告诉您x是否小于y。
x.compareTo(y) > 0
will 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在进行这些调用之前是非null是明智的。
#9
1
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)来使其工作。
#1
32
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()。
#2
26
Use the equals
method. Why are you so worried that it's expensive?
使用equals方法。你为什么这么担心它的价格昂贵?
#3
12
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.
这不是一项昂贵的操作,也没有计算哈希码。 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 int
values.
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.
注意:不要过早地应用微优化;你的假设如“这必须很慢”很可能是错误的或无关紧要,因为代码不是性能瓶颈。
#4
8
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);
#5
8
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类有一个静态比较(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兼容。
#6
2
"equals" is it. To be on the safe side, you should test for null-ness:
“等于”就是这样。为了安全起见,您应该测试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经常被调用,那么代码将由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)相同,但如果其中一个为null,则不需要。
#7
2
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接口并覆盖其compare方法并比较其值,如下所示:
@Override
public int compare(Integer o1, Integer o2) {
if (ascending) {
return o1.intValue() - o2.intValue();
} else {
return o2.intValue() - o1.intValue();
}
}
#8
1
The Integer class implements Comparable<Integer>
, so you could try,
Integer类实现了Comparable
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将告诉您x是否小于y。
x.compareTo(y) > 0
will 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在进行这些调用之前是非null是明智的。
#9
1
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)来使其工作。