Java隐式转换char到int?

All*_*len 0 java int type-conversion char

我接受了一个面试问题,以输出最常出现的角色.

鉴于此字符串"aaxxaabbaa".字符'a'是最常见的.

以下代码是我在互联网上搜索的内容.注意:我用2个循环实现了它,效率不高(不同主题)

public static char findMostUsedChar(String str){
    char maxchar = ' ';
    int maxcnt = 0;
    // if you are confident that your input will be only ascii, then this array can be size 128.
    // Create a character counter
    **int[] charcnt = new int[Character.MAX_VALUE + 1];**
    for(int i = 0; i < str.length()-1; i++){
        char **ch** = str.charAt(i);
        // increment this character's cnt and compare it to our max.
        if (**charcnt[ch]**++ >= maxcnt) {
            maxcnt = charcnt[ch];
            maxchar = ch;
        }
    }
    return maxchar;
}
Run Code Online (Sandbox Code Playgroud)

他们声明了一个int数组,在特定索引(即'a')处找到该字符,然后用作索引.在eclipse中的调试器上跟踪代码之后,我仍然不明白如何使用字符来表示int索引,而无需显式地使用它或使用charVal.getNumericValue()?甚至大多数SO char到int主题都明确地转换了.

提前致谢.

rge*_*man 5

数组访问表达式经历隐式一元数字提升,这将扩展表达式int.

索引表达式经历一元数字推广(第5.6.1节).

char数据类型被加宽到int经由它的Unicode值,例如'A'- > 65.