java如何将变量的数据与ArrayList中的数据进行比较?
我正在调用一个传入变量的方法。我希望能够将此变量与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");
}
}
}
我的代码没有像我预期的那样工作。有人能帮我解决这个问题吗
# 1 楼答案
我认为checkItem变量是一个字符串列表,因此应该这样定义:
比较字符串时,不使用string1==string2,而是使用string1。等于(2)
所以
应该是:
记住检查字符串中的空值
所以整个代码可以如下所示: