从数组到字符串的隐式转换¶
ID: java/print-array
Kind: problem
Security severity:
Severity: recommendation
Precision: very-high
Tags:
- maintainability
Query suites:
- java-security-and-quality.qls
打印数组可能会产生意外结果。也就是说,结果不包含数组的内容。这是因为数组使用 Object.toString
隐式转换为 String
,它只会返回以下值
getClass().getName() + '@' + Integer.toHexString(hashCode())
建议¶
将数组转换为可读字符串时,对一维数组使用 Arrays.toString
,对多维数组使用 Arrays.deepToString
。这些函数会迭代数组内容并生成人类可读的输出。
示例¶
在以下示例中,只有在首先对数组调用 Arrays.toString
的情况下,才会打印出数组 words
的内容。类似地,只有在首先对数组调用 Arrays.deepToString
的情况下,才会打印出多维数组 wordMatrix
的内容。
public static void main(String args[]) {
String[] words = {"Who", "is", "John", "Galt"};
String[][] wordMatrix = {{"There", "is"}, {"no", "spoon"}};
// BAD: This implicitly uses 'Object.toString' to convert the contents
// of 'words[]', and prints out something similar to:
// [Ljava.lang.String;@459189e1
System.out.println(words);
// GOOD: 'Arrays.toString' calls 'toString' on
// each of the array's elements. The statement prints out:
// [Who, is, John, Galt]
System.out.println(Arrays.toString(words));
// ALMOST RIGHT: This calls 'toString' on each of the multi-dimensional
// array's elements. However, because the elements are arrays, the statement
// prints out something similar to:
// [[Ljava.lang.String;@55f33675, [Ljava.lang.String;@527c6768]]
System.out.println(Arrays.toString(wordMatrix));
// GOOD: This properly prints out the contents of the multi-dimensional array:
// [[There, is], [no, spoon]]
System.out.println(Arrays.deepToString(wordMatrix));
}
参考¶
Java API 规范:Arrays.toString()、Arrays.deepToString()、Object.toString()。