tom
tom

Reputation: 5504

Java for loop iteration

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?

Upvotes: 0

Views: 179

Answers (2)

Alexis C.
Alexis C.

Reputation: 93842

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.

Upvotes: 5

John Kugelman
John Kugelman

Reputation: 361710

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");

Upvotes: 5

Related Questions