0

In my application, I have list of values of type String, I am iterating throught it and comparing the values of each to another string and if it is true returning true value else false.

List<String> roleNames = new ArrayList<String>();
roleNames.add("AAA");
roleNames.add("MMM");
for (int i=0 ; i<roleNames.size();i++){
//  if(loggedInRole.equals(roleNames.get(i))){
    if("AAA".equals(roleNames.get(i))){
        enableLink = "true";
    }
    else {
        enableLink = "false";
    }
}

In my above code i am expecting the result as true but in the second itertion it returning the result as false. How to reolve this issue?

3
  • 1
    Well in the second iteration the value is "MMM", not "AAA"... is that really your complete loop? Note that you're not actually returning anything... Commented Jan 14, 2014 at 17:06
  • why did u not declare enableLink as a boolean? Commented Jan 14, 2014 at 17:08
  • 4
    hint: instead of looping through the ArrayList you can just have enableLink = roleNames.contains("AAA"); Commented Jan 14, 2014 at 17:09

2 Answers 2

5

Add a break statement when you find a match. If you don't break out of the loop then the next iteration will set enableLink back to "false" when it iterates over "MMM".

Also you should set enableLink to "false" before you start the loop. The standard "search an array" loop looks like:

enableLink = "false";

for (int i = 0; i < roleNames.size(); i++) {
    if ("AAA".equals(roleNames.get(i))) {
        enableLink = "true";
        break;
    }
}

For what it's worth, you don't need an explicit loop. You could write:

boolean enableLink = roleNames.contains("AAA");
Sign up to request clarification or add additional context in comments.

1 Comment

Its as simple as that, thank you so much for reminding me of BREAK, It worked.Thank you a TONE
5

You have to break the loop when you found one value that satisfied your condition, otherwise enableLink will be "true" only if the last element of your list is equals to "AAA" in your case.

You should also look at the contains method.

Comments

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.