简体   繁体   中英

Enhanced for loop - JAVA

I'm always confused with enhanced for loop. I have this example

public class NonRepeatedChar
{   
    public static void main(String[] args)
    {
        String str = "javapassion";
        int[] count = new int[128];
        char[] charArr = str.toLowerCase().toCharArray();
        for (char c : charArr)
        {
            count[c]++; 
        }
        for (char c : charArr)
        {
            if (count[c] == 1)
            {      
                System.out.println("First Non repeated character is : " + c);
                break;
            }
        }
    }
}

So in the above in the first for loop it says count[c]++ , this means a new array count is initialised and value of c is stored while the iterator is incremented ?

c is, in turn, each char in your String, that is, it takes the values 'j', 'a', 'v' etc.
Each char in Java is a 16 bit value with the normal latin lower-case character being values less than 128.
So count[c]++ increments the array cell corresponding to that character (counts occurrences of it).

c is used as an array index. It just so happens that in unicode (and ASCII) the 'normal' characters have a base 10 decimal value of between 0 and 127 . Therefore, the integer value of any ASCII character sequence that you'd supply to the program is always going to be between 0 and 127. (You can still supply non-ASCII (unicode) characters to Java, of course, but in the context of this example I'm guessing they wanted to keep it simple .) This also has the benefit (because the String is converted to lowercase) of giving you the answer sorted alphabetically.

The array count stores the number of times an individual character has been found (seeing as the character is used as the index). The line count[c]++ increments the entry for the character c . If the count exceeds one then it becomes a repeated character and thus won't be printed out at the end.

Let's separate your two questions:

(A) what is a for loop

(B) what's going on with the operations on the count[] array


(A)

The for loop is just a way to traverse a collection or array so as to visit each member in said collection.

(B)

  • the for loop iterates over the characters in "javapassion"
  • each character (c) has an ascii value that is used as the array index in count[c]
  • count[c]++ increments the value at count[c] for each letter c
  • in the end, the resulting count[] array contains the number of occurrences of each letter found in the the input string

To learn the magic of the enhanced for loop, try expanding it into a regular for loop. For example, the first loop

for (char c : charArr)
{
    count[c]++; 
}

becomes

for (int i = 0; i < charArr.length; i++)
{
    char c = charArr[i];
    count[c]++;
}

So the enhanced for loop is less code, making it easier to type and read, but you do not have access to the index i.

The enhanced for loop also works for Iterable objects, like collections, but expands into different code. Try expanding that based on the behavior above and the Iterable interface .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM