我希望能够使用 < > == 来比较两个列表中的元素。
使用 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
}
您正在以正确的方式操作。
如评论所述,您也可以使用compareTo()
。
equals()
是compareTo()
的另一种选择,它不会在对象为空的情况下抛出NullPointerException。
a.get(0).intValue() == b.get(0).intValue()
2)
a.get(0).equals(b.get(0))
您的代码存在问题,您需要使用get(0)而不是get(1)。请记住,在Java中始终从0开始。
值也可以使用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");
}
}
}
a.get(1).compareTo(b.get(1)) == 0
。 - Luiggi Mendoza