Writing in the front

If you find it helpful, remember to click on the following and click on the like oh, will be greatly appreciated. In Java, an array is an object, but such a class is not explicitly defined, so there is no opportunity to override the toString() method. If we try to print the array directly, the output is not what we expect. Are there some simple ways to do this? This seems like a simple question, and everyone knows how to print an array, but think about how many different ways you can print, and which one is the most elegant and compact?

Print directly

Curious, isn’t it, why you can’t just print an array using system.out.println () and other methods? Here’s an example.

int[] intArray = new int[] {1.2.3.4.5};
String[] stringArray = new String[] {"1"."2"."3"."4"."5"};
System.out.println(intArray);
System.out.println(stringArray);
Copy the code



Let’s analyze the printout, where[I[Ljava.lang.String;Representing arrays of integers and stringsClassName,@It’s in hexadecimalhashCode— This print result is too “humanized”, the average person says can’t understand! Why is it displayed this way? As we all know, classes in Java inherit fromjava.lang.Object, check it outjava.lang.ObjectOf the classtoString()The method is as follows.



From this we know that in Java, an array is not explicitly defined as a class, but it is an Object that inherits all the methods of its Object ancestor. So why not define a separate class for arrays? Like the String class? One plausible explanation is that Java hides it. If there is an array.java, as we can imagine, it must define a container to hold the elements of an Array, just like the String class.

Who cares? The cycle of violence?

When printing arrays in Java, the first thing many people think of is looping. A for loop destroys everything. Use a for loop to print arrays in sequence, even for-each.

for(int i = 0; i < cmowers.length; i++){
    System.out.println(cmowers[i]);
}
for (String s : cmowers) {
	System.out.println(s);
}
Copy the code

Printing in this way can indeed complete our requirements, but for this kind of beginner programming should master for to complete our requirements, it is really not enough, we should use a more elegant way to complete our requirements.

Arrays.toString()

It has been available since Java5Arrays.toString()Print an array,Arrays.toString()You can convert arrays of any type to strings, including primitive and reference arrays,Arrays.toString()Is called for each element object in the array.toString(), so we can override the element object’s.toString()To complete our customized output, I post the method below.



This class contains convenient methods for manipulating arrays and is namedArraysLet’s call itArrayUtil. useArrays.toString()Method is an elegant way to print an array, so let’s use it here and see what it looks like

String[] array = new String[] {"John"."Mary"."Bob"};
System.out.println("Example 1:" + Arrays.toString(array));

double[] doubleArray = { 7.0.9.0.5.0.1.0.3.0 };
System.out.println("Example 2:" + Arrays.toString(doubleArray));

int[] intArray = { 7.9.5.1.3 };
System.out.println("Example 3:" + Arrays.toString(intArray));

String[][] deepArray = new String[][] {{"John"."Mary"}, {"Alice"."Bob"}};
System.out.println("Example 4:" + Arrays.toString(deepArray));
Copy the code



Look at the output above, print in no more than no less! The first three are exactly what we expect: [] indicates an array, “, “and Spaces are used to split elements. Example 4 does not meet our expectationsArrays.toString()You can’t print multidimensional arrays.Arrays.toString()By calling the element objecttoString()Method, while the arraytoString()Of course it didn’t work out as well as we’d hoped, but there was a way to do it, we’ll say laterArrays.toString()Method source, as follows

  • If the array isnull“, then return"Null"String, well thought out, left outNullPointerExceptionThe trouble.
  • If the array length is zero0“, then return"[]"A string. Note that it is not used herea.length == 0Call short, but usea.length - 1 == -1And for the laterforIn the loopi == iMaxForeshadowing, resources are not wasted.
  • forThe concatenation of strings in loops is even more subtle,forThere is no judgment in the condition of the loopi < a.lengthIn the circulatory systemi == iMaxWhat’s the good of that? In general, the average programmer does this when concatenating strings.
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; i < cmowers.length; i++) {
    b.append(cmowers[i]);
    b.append(",");
}
b.delete(b.length()-2, b.length());
b.append('] ');
Copy the code

Right? It’s pretty neat, but it pales in comparison to the toString() method in the source code. The quickest way to become a good programmer, not just an average programmer, is to learn the Java source code.

Arrays.deepToString()

As mentioned above, arrays.tostring () is useless if you need to print multi-dimensional Arrays.

String[][] deepArray = new String[][] {{"John"."Mary"}, {"Alice"."Bob"}};
System.out.println("Example 4:" + Arrays.toString(deepArray));
Copy the code

The output is as follows:

Example 4: [[ljava.lang.string;@6d6f6e28, [ljava.lang.string; @135fbaA4]Copy the code

No, no, no. This is not what we wanted. What do we do? Use arrays.deepToString (), made for multi-dimensional Arrays.

String[][] deepArray = new String[][] {{"John"."Mary"}, {"Alice"."Bob"}};
System.out.println(Arrays.deepToString(deepArray));
Copy the code



Let’s take a look at the old rulesArrays.deepToString()The source code!

Stream

If you are using JDK8 or higher, you can Stream through the groups in a stylish, fashion fashion and print them out as you go along.

String[] array = new String[] {"John"."Mary"."Bob"};
Arrays.asList(array).stream().forEach(s -> System.out.println(s));
Stream.of(array).forEach(System.out::println);
Arrays.stream(array).forEach(System.out::println);
Copy the code



All three of these approaches are easy to do their job with, and are a little bit patronizing, given the Stream and lambda expressions. Note, however, that these three methods still do not complete the printing of multidimensional arrays, so relatively speaking, there is no comparisonArrays.toString()Grace.

String.join()

String[] array = new String[] {"John"."Mary"."Bob"};
System.out.println(String.join(",", array));
Copy the code



This still doesn’t print a two-dimensional array.