java中如何比较两个整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23116143/
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
How to compare two Integers in java
提问by user3495562
I want to compare elements in two list using < > ==
我想使用 < > == 比较两个列表中的元素
Is it the right way to use intValue()?
这是使用 intValue() 的正确方法吗?
List<Integer> a = new ArrayList<Integer>();
a.add(129);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() > b.get(o).intValue()) {
// something
}
采纳答案by user3495562
You're making it the right way.
你做对了。
As stated in the comments, you could also you compareTo()
.
An alternative to compareTo()
is equals()
which won't throw a NullPointerException in the case where the object is null.
正如评论中所述,你也可以compareTo()
。另一种方法compareTo()
是equals()
在对象为空的情况下不会抛出 NullPointerException。
回答by Sireesh Yarlagadda
Your way is correct. But with a small correction.
你的方法是对的。但有一个小的修正。
1)
1)
a.get(0).intValue() == b.get(0).intValue()
2)
2)
a.get(0).equals(b.get(0))
This is the problem in your code, you have to get(0), instead of get(1). Remember, in java it always start with 0.
这是您代码中的问题,您必须使用get(0)而不是get(1)。请记住,在 Java 中它总是以 0 开头。
Values can be compared using equals()
or CompareTo method as well.
也可以使用equals()
或 CompareTo 方法比较值。
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> a= new ArrayList<Integer>();
a.add(128);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() == b.get(0).intValue()){
System.out.println("success");
}else{
System.out.println("failure");
}
if(a.get(0).equals(b.get(0))){
System.out.println("success");
}else{
System.out.println("failure");
}
}
}