Array access with char index in Java

跟風遠走 提交于 2020-01-30 07:56:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!