-1

So I have an arraylist and a string. I have to compare whether the arraylist contains the string. I did "ArrayList.toString()" to convert it to string since I can't compare an arraylist with a string. And then I proceeded to use .contains. It sort of works.

For example, let's say if String 1= "ground" and in String 2 the word "playground" exists, then it would make the .contains true because the word "ground" is inside the word "playGROUND". Is there anyway to avoid this? The arraylist had some first letters caps so I set it .tolowercase so everything could be uniform. I've tried .equals and .equalsIgnorecase and no luck. :/

5
  • 1
    Hard to understand what all you have written here? Jul 21, 2015 at 13:23
  • 3
    You may need to iterate over the list and check each item against the word
    – depperm
    Jul 21, 2015 at 13:24
  • I recommend you posting some code, also, can you use a for loop ? Simply compare the strings one by one ...
    – Raphaël
    Jul 21, 2015 at 13:24
  • arraylist.toString() doesn't do what you think it does docs.oracle.com/javase/7/docs/api/java/util/… Jul 21, 2015 at 13:24
  • If you are iterating over the words, you should use equals() or equalsIgnoreCase() depending on your use case Jul 21, 2015 at 13:30

2 Answers 2

1

i have to compare whether the arraylist contains the string. i did "ArrayList.toString()" to convert it to string since i cant compare an arraylist with a string.

You can also use contains method on ArrayList<String>

for example, lets say if String 1= "ground" and in String 2 the word "playground" exists, then it would make the .contains true because the word "ground" is INSIDE the word "playGROUND". Is there anyway to avoid this?

Yes use contains method of arrayList it will not return true for ground if it has playGround.

Ive tried .equals and .equalsIgnorecase and no luck :/

You have to loop over the arrayList and than use equalsIgnorecase on each String to find the match.

1
  • 1
    I'm glad you could understand what he was talking about for his 3rd part plus a good explanation. +1
    – Adam
    Jul 21, 2015 at 13:31
0

Question 1:

Iterate through your list and compare each value to the string for comparison.

for(string temp: yourList)
   if(temp.equals(stringForCompare))
       //true
//false

Question 2:

if(string2.contains(string1) && !string2.equals(string1)) is the logic you are explaining in your question which makes no sense and can be simplified to if(!string2.equals(string1).

Question 3:

Not even sure what you're asking but @TAsk has it pretty well answered it looks.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.