将 arraylist 中的元素与 java 中的整数值进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16952477/
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
comparing element in arraylist with an integer value in java
提问by Kris
I have loaded the contents of the database in an ArrayList named countList. The contents loaded are of int type. I created countList using the command
我已将数据库的内容加载到名为 countList 的 ArrayList 中。加载的内容为 int 类型。我使用命令创建了 countList
ArrayList countList = new ArrayList();
ArrayList countList = new ArrayList();
Now, I need to check if each contents of the arraylist is greater than three. I wrote it like
现在,我需要检查 arraylist 的每个内容是否大于三个。我写的像
for(int i=0; i< itemset.size(); i++){
if(countList.get(i) >= 3)
{
}
}
When I write it simply, it shows error of bad operand type for binary operator '>='. How to do the task?
当我简单地写它时,它显示二元运算符'> ='的错误操作数类型错误。怎么做任务?
回答by devrobf
The >=
operator is only defined on number types such as int
, double
or Integer
, Double
. Now, countlist
may wellcontain integers (I assume it does), but the way you have written your code, the compiler can't be sure. This is because an ArrayList
can store any type of object, including but not necessarily Integer
. There are a couple of ways you can remedy this:
所述>=
操作者仅在数类型,如所定义int
,double
或Integer
,Double
。现在,很countlist
可能包含整数(我认为确实如此),但是根据您编写代码的方式,编译器无法确定。这是因为 anArrayList
可以存储任何类型的对象,包括但不一定Integer
。有几种方法可以解决这个问题:
a) You can castthe ArrayList item to an Integer
, at which point the >=
operator will work:
a) 您可以将ArrayList 项转换为Integer
,此时>=
运算符将起作用:
if ( (Integer) countList.get(i) >= 3)
b) You can use genericsto tell the compiler that your ArrayList
will ONLY store Integer
s:
b) 您可以使用泛型告诉编译器您ArrayList
将只存储Integer
s:
ArrayList<Integer> countList = new ArrayList<Integer>();
回答by Farid Mohd Nor
for(i=0; i< itemset.size(); i++){
if (itemset.get(i) > 3) {
// Do whatever you want here
}
}