When you want to display an array on the console in Java, you used to write a for statement etc., but you can easily display it by using the Arrays.toString method.
sample
int[] a = {1, 2};
//So far
for (int i: a) {
System.out.println(i);
}
//Or
Arrays.stream(a).forEach(System.out::println);
//from now on
System.out.println(Arrays.toString(a));
//Caution
System.out.println(a.toString());
console
1
2
1
2
[1, 2]
[I@bebdb06
Comparing the above three things, the Arrays.toString method is the cleanest. I think the method using Stream API is also good, but Arrays.toString is better because it is difficult to describe when dealing with multidimensional arrays.
By the way, if you do a.toString () like the last one, the hash value of the array variable will be displayed. Also, in standard output methods such as System.out.println, the argument toString () is called internally, so refrain from redundant writing such as System.out.println (sb.toString ()) ;. Let's do it.
Use the deepToString method.
String[][] sss = {{"a","bb"}, {"ccc"}};
System.out.println(Arrays.toString(sss));
System.out.println(Arrays.deepToString(sss));
console
[[Ljava.lang.String;@bebdb06, [Ljava.lang.String;@7a4f0f29]
[[a, bb], [ccc]]
If you want to output an array as standard, use the ** Arrays.toString ** and ** Arrays.deepToString ** methods.
Recommended Posts