通过字符访问数组项的代码令人困惑

时间:2018-07-26 15:23:37

标签: java arrays character

我在网上找到了此代码,它返回字符串中最常见的字符。在下面指示的点上,我们有表达式++charcnt[ch]。据我了解,charcnt是int[],任何数组的元素都必须通过一个整数来访问,该整数指示特定元素的索引号。 ch是一个字符,但是...我运行了代码,没有错误。为什么没有给出错误?我了解我们正在尝试增加计数,但是我不了解您应该如何使用字符访问数组。任何澄清将不胜感激。

public static char getMax(String word) {
    if (word == null || word.isEmpty()) {
        throw new IllegalArgumentException("input word must have non-empty value.");
    }
    char maxchar = ' ';
    int maxcnt = 0;
    // if you are confident that your input will be only ascii, then this array can be size 128.
    int[] charcnt = new int[Character.MAX_VALUE + 1];
    for (int i = word.length() - 1; i >= 0; i--) {
        char ch = word.charAt(i);
        // increment this character's cnt and compare it to our max.
        if (++charcnt[ch] >= maxcnt) {    #HERE
            maxcnt = charcnt[ch];
            maxchar = ch;
        }
    }
    return maxchar;
}

4 个答案:

答案 0 :(得分:2)

JLS Array Access强调我的

  

数组必须由int值索引;短,字节或 char 值也可以用作索引值,因为它们会受到一元数值提升(§5.6.1)和成为int值的作用。

答案 1 :(得分:0)

当您尝试访问带有字符的整数数组时,Java会自动将字符转换为其ASCII值。

答案 2 :(得分:0)

根据Java规范

  

数组必须由int值索引; short,byte或char值可能   也可以用作索引值,因为它们会受到一元   数字提升(第5.6.1节)并成为int值。尝试访问   具有长索引值的数组组件会导致编译时   错误。

https://www.cs.cornell.edu/andru/javaspec/5.doc.html#170952

答案 3 :(得分:-2)

ASCII码具有128个不同的字符,其整数值从0到127。 例如,char A的值为65,表示它可用于指向maxcnt递增其计数器的第66个单元格。