1

Using regular foloop, getting correct output, using for each loop throws ArrayOutOfBound exception. Can anyone explain?

public class FindTheDiff {
public static void main(String args[]){
    System.out.println(isAnagramRecursion("all","laa"));
}

private static boolean isAnagramRecursion(String param1, String param2) {
    int[] arr = new int[122];
    char[] param1Lower = param1.toLowerCase().toCharArray();
    char[] param2Low2 = param2.toLowerCase().toCharArray();

    for (char ch1 : param1Lower) {
        arr[ch1] = arr[ch1]+1;
    }

    for (char ch2 : param2Low2){
        arr[ch2] = arr[ch2]-1;
    }

    for (int i :arr) {
        if(arr[i] != 0)
            return false;
    }
    /*for (int i = 0; i < arr.length; i++) {
        if(arr[i] != 0)
            return false;
    }*/
    return true;
}

}

0

2 Answers 2

2

This is the wrong loop. When doing a forEach loop, you iterate over the value, not the index. The correct forEach loop in your case should be:

for (int arrValue :arr) {
    if(arrValue != 0)
        return false;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here i is not the index of the array, it's the value of the array. But in the regular loop i is the index.

for (int i :arr) {
    if(arr[i] != 0)
       return false;
}

Use the value of the array means i in if condition

for (int i :arr) {
    if(i != 0)
        return false;
}

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.