【发布时间】:2020-10-23 04:14:58
【问题描述】:
atm 我正在做一个 Java 练习,它是关于将整数与 ArrayList 的所有元素进行比较。根据书的解决方案应该是与“int index = ArrayList.indexOf(comparisonValue);”的比较和“索引> = 0”。 但对我来说,它不起作用。我还读到“indexof”只检查 ArrayList 的第一个位置。但如果这是真的,为什么在我的书中这被标记为正确的解决方案?
也许我遇到了错误。这是我的代码,谢谢 :)
ArrayList<Integer> tiplist = new ArrayList<Integer>(20);
int des = 0;
int limit = 20;
int tipc = 0;
int index = tiplist.indexOf(tip);
//program loop:
while (des == 0 && tipc < limit) {
tip = 6; //I made it easy to read, normally the number is generated
tipc++; //tip count
if (tipc > 1) { //if it is not the first tip
这不起作用:
if (index >= 0) {
System.out.println("Nothing new");
}
但确实如此,虽然我读到“包含”也使用“indexof”:
if (tiplist.contains(tip) == true) {
System.out.println("Nothing new");
}
最后几行...
}
tiplist.add(tip);
// -->do something
}
【问题讨论】:
-
在
if (index >= 0) {中,index不会在循环的每次迭代中更新,因此它使用您在循环之前计算的值。虽然if (tiplist.contains(tip) == true) {使用indexOf,但它会在每次循环迭代时重新评估indexOf。 -
欢迎来到 StackOverflow!你能提供一个minimal reproducible example吗?此外,如果您可以编辑以删除“thx”或“atm”等聊天术语,那就太好了:)
标签: java arraylist contains indexof