使用 "char" 与 "int" 索引数组,有什么区别?
Indexing an array using "char" vs "int", what is the difference?
在 "Cracking the Coding Interview" 中有一题要你检查两个字符串是否是彼此的排列。看完代码后,我很困惑为什么作者的示例实现使用第一个字符串的 "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
.
在功能上完全相同
在 "Cracking the Coding Interview" 中有一题要你检查两个字符串是否是彼此的排列。看完代码后,我很困惑为什么作者的示例实现使用第一个字符串的 "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
.