0

I am trying to check if an arraylist B contains a string from arrayA with this, but it doesn't work:

String match = arrayA[i];
if (! B.contains(match)) {
    outputFile.print(match);
}

Is this because I used the contains() method incorrectly?
Can we put the name of the variable in the contains() method like contains(match) here?
Or do we have to put a string in the contains(), like contains("name")?

4
  • 1
    The condition in your if statement is negated (indicated by the "!"), meaning that you only print stuff to the file if they DONT match. Are you sure that that's what you want? Commented Apr 16, 2014 at 7:31
  • You say it "doesn't work". Could you be more specific? What happens? Commented Apr 16, 2014 at 7:33
  • Note that "name" and a String with the value "name" will work the same way here. If I'm not mistaken they'll even point to the same String literal in memory. The difference is that the second one has a variable associated with it. Commented Apr 16, 2014 at 7:34
  • For more information look at this Commented Apr 16, 2014 at 7:38

1 Answer 1

1

In

  if (! B.contains(match))

you check, if B does NOT contain match. Apart from that, the approach is valid.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Christian! Yes I am trying to print out the elements that are not in the arraylist B.
Then your contains is correct. Is your program crashing?
No it's not crashing, but it does not print out the String match properly. Maybe it's because of the other methods but not this contains(). I will check it again. Thanks, the confirmation really helpful!
I'm guessing from the index i that you're doing this in a loop iterating over arrayA. Are you sure that arrayA is initialized and contains what you think it contains? Try adding an else clause that prints elements that are not in B. If nothing is printed, then you'll know that arrayA doesn't contain what you expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.