我已将数据库的内容加载到名为 countList 的 ArrayList 中。加载的内容是int类型。我使用命令创建了 countList
ArrayList countList = new ArrayList();
现在,我需要检查 arraylist 的每个内容是否大于 3。我这样写
for(int i=0; i< itemset.size(); i++){
if(countList.get(i) >= 3)
{
}
}
当我简单地编写它时,它显示二元运算符“> =”的错误操作数类型错误。任务怎么做?
最佳答案
>=
运算符仅在数字类型上定义,例如 int
、double
或 Integer
、双
。现在,countlist
很可能包含整数(我认为确实如此),但是编译器无法确定您编写代码的方式。这是因为 ArrayList
可以存储任何类型的对象,包括但不一定是 Integer
。有几种方法可以解决这个问题:
a) 您可以将 ArrayList 项转换为 Integer
,此时 >=
运算符将起作用:
if ( (Integer) countList.get(i) >= 3)
b) 您可以使用泛型告诉编译器您的ArrayList
将仅存储Integer
:
ArrayList<Integer> countList = new ArrayList<Integer>();
关于java - 将 arraylist 中的元素与 java 中的整数值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952477/