I am calling a method that passes in a variable. I want to be able to compare this variable to all the items in an ArrayList to see if there is a match.
This is my code…
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");
}
}
}
My code isn’t working as I had expected. Could someone please help me fix the problem.
I take it that the checkItem variable is a List of Strings, thus it should be defined like this:
When comparing an String you don’t use string1==string2 but string1.equals(string2);
So
should be:
Remember to check the string for null values.
So the whole code could look like this: