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?
int i = c; if (++count[i] == 2)is what is happening, where one can have an IndexOutOfBoundsException for non-ASCII (§ é € ½ ©)new int[Character.MAX_VALUE+1]would cover all UTF-16 code units. It probably wouldn't be useful for Unicode codepoints that UTF-16 encodes in two code units 😉, nor for grapheme clusters (aka "user-percieved characters"). But is seems you expect only the C0 Controls and Basic Latin characters.