Array access with char index in Java

Pepe Carval :

While seeing the explanation for a Java programming exercise online, I came upon the following piece of code:

int[] count = new int[128];
int length = 0;
for(char c: s.toCharArray()){
    if(++count[c] == 2){
        length += 2;
        count[c] = 0;
    }
}

I understand what the code does but I don't know how it can access an array element using a char index (i.e.count[c], where c is a char). I thought indexes could only be integers?

Sordinho :

A char (16 bit) is an int (32 bit), not vice versa. This is an implicit casting, char to unsigned int in particular. In this case, the index will probabily be the ASCII code representing this char (for ASCII characters).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143979&siteId=1