【问题标题】:Java Implicit conversion char to int?Java隐式转换char到int?
【发布时间】:2015-10-06 23:34:47
【问题描述】:

我得到了一个面试问题,以输出一个字符出现频率最高的情况。

给定这个字符串“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;
}

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

提前致谢。

【问题讨论】:

标签: java char int type-conversion


【解决方案1】:

Array access expressions 进行隐式一元数字提升,这会将表达式扩展为 int

索引表达式经历一元数字提升(第 5.6.1 节)。

char 数据类型通过其 Unicode 值扩展为 int,例如'A' -> 65.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 2014-02-14
    • 2013-10-05
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    相关资源
    最近更新 更多