我正在调用一个传递变量的方法。我希望能够将此变量与 ArrayList 中的所有项目进行比较,以查看是否存在匹配。
这是我的代码...
private boolean input;
private ArrayList chcekItem = new ArrayList();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
}
else {
Iterator iterators = getChcekItem().iterator();
while (iterators.hasNext()) {
if (iterators.next()==action) {
System.out.println(iterators.next()+"="+action);
input=false;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}
else{
System.out.println("The item " + action + " is Exist");
}
}
}
我的代码没有按我的预期运行。有人可以帮我解决这个问题吗?
最佳答案
我认为 checkItem 变量是一个字符串列表,因此它应该这样定义:
private List<String> checkItem = new ArrayList<String>();
比较字符串时,不使用 string1==string2 而是使用 string1.equals(string2);
所以
(iterators.next()==action)
应该是:
(iterators.next().equals(action))
记住检查字符串中是否有空值。
所以整个代码可能如下所示:
private boolean input;
private List<String> chcekItem= new ArrayList<String>();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
} else {
//Foreach loop instead of an iterator ;)
for(String item : chcekItem) {
if(item.equals(action)) {
System.out.println(item+"="+action);
input=false;
//We can jump out of the loop here since we already found a matching value
break;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}else{
System.out.println("The item " + action + " is Exist");
}
}
}
}
关于java - 如何将变量的数据与 ArrayList 中的数据进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11176163/