gpt4 book ai didi

java - 使用 "char"与 "int"索引数组,有什么区别?

转载 作者:行者123 更新时间:2023-12-01 17:43:38 26 4
gpt4 key购买 nike

在“破解编码面试”中,有一个问题要求您检查两个字符串是否是彼此的排列。查看代码后,我很困惑为什么作者的示例实现使用第一个字符串的“char”值来索引数组,然后获取第二个字符串的 char 值,但在访问相同的字符串之前将其转换为 int大批。这是下面的代码片段。您可以看到,在第一个 for 循环中,它使用 char 值,但在第二个 for 循环中,它在访问之前将 char 转换为 int。:

    boolean isPermutation(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}

int[] charCount = new int[128];

char[] s_array = str1.toCharArray();
for (char c : s_array) {
charCount[c]++;
}

for (int i = 0; i < str2.length(); i++) {
int c = (int) str2.charAt(i);
charCount[c]--;
if (charCount[c] < 0) {
return false;
}
}
return true;
}

最佳答案

使用 char 索引数组的方式与使用 int 索引数组的方式几乎完全相同。来自 the JLS :

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values.

因此,当您使用 char 索引数组时,char 首先会提升为其相应的 int 值,然后用于索引数组。从用户的角度来看,最终结果是使用 char 的行为与使用 int 的功能相同。

关于java - 使用 "char"与 "int"索引数组,有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57997585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com