问题
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?
回答1:
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).
回答2:
The char is implicitly cast to an int. The index is still an int.
回答3:
So Basically Each Character is defined by Ascii value. So when you try to use char as int. It will use it as defined Ascii value.
That's why its working.
来源:https://stackoverflow.com/questions/57773977/array-access-with-char-index-in-java