Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5c5d700

Browse files
author
zhupeiquan
committed
What\'s_the_simplest_way_to_print_a_Java_array.md 添加
1 parent f644ddf commit 5c5d700

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# 输出 Java 数组最简单的方式
2+
3+
## 问题
4+
因为 Java 数组中没有 toString() 方法,所以直接输出如下数组,输出显得并人性化:
5+
```
6+
int[] intArray = new int[] {1, 2, 3, 4, 5};
7+
System.out.println(intArray); // prints something like '[I@3343c8b3'
8+
```
9+
10+
有什么方式可以实现如下的输出效果?
11+
```
12+
// array of primitives:
13+
int[] intArray = new int[] {1, 2, 3, 4, 5};
14+
//output: [1, 2, 3, 4, 5]
15+
16+
// array of object references:
17+
String[] strArray = new String[] {"John", "Mary", "Bob"};
18+
//output: [John, Mary, Bob]
19+
```
20+
21+
## 解答
22+
23+
在 Java 5+ 以上,可以使用 Arrays.toString(arr) 输出数组的值,使用 Arrays.deepToString(arr) 输出多维数组的值.提示,数组中的对象都会调用 toString() 方法输出其值。
24+
25+
首先,引入对应的包:
26+
```
27+
package packageName;
28+
import java.util.Arrays;
29+
...
30+
```
31+
32+
例子:
33+
```
34+
// simple array
35+
String[] array = new String[] {"John", "Mary", "Bob"};
36+
System.out.println(Arrays.toString(array));
37+
//output: [John, Mary, Bob]
38+
39+
// nested array
40+
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
41+
System.out.println(Arrays.toString(deepArray));
42+
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
43+
System.out.println(Arrays.deepToString(deepArray));
44+
//output: [[John, Mary], [Alice, Bob]]
45+
```
46+
47+
对于原始类型的数组,其本质就是将原始类型转换为对应包装类型,然后调用其 toString() 方法输出其值。
48+
49+
stackoverflow原址:http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /