更新時間:2022-07-26 11:34:34 來源:動力節(jié)點(diǎn) 瀏覽1741次
當(dāng)我們對 java 對象數(shù)組進(jìn)行打印的時候,會遇到輸出內(nèi)容是 className + '@' + 16 進(jìn)制的 hashcode 組成的字符串,Java數(shù)組輸出的方式主要有以下 3 種方式。
從 java 1.5 之后,針對簡單的數(shù)組(如一維數(shù)組),可以使用 Arrays.toString(arr),具體如下:
String[] array = new String[] {"Knowledge", "Dict", "Good"};
System.out.println(Arrays.toString(array));
輸出如下:
[Knowledge, Dict, Good]
需要強(qiáng)調(diào)的是,除了基本類型及 String 這種已經(jīng) toString 方法打印內(nèi)容邏輯之外,其他封裝的類對象要在 toString 方法里 override 內(nèi)容輸出。
數(shù)組的打印,本質(zhì)上是執(zhí)行每個對象的 toString 方法。
也是從 java 5 之后,針對嵌入的數(shù)組(Nested Array),如二維數(shù)組,數(shù)組里面再嵌套其他數(shù)組的,可以用 Arrays.deepToString(deepArray) 靜態(tài)方法。
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
輸出:
[[John, Mary], [Alice, Bob]]
可以通過 for 循環(huán),自定義打印輸出的內(nèi)容。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743