Browsing Stack Overflow, we’ve come across some high-volume questions like this one: What’s the most elegant way to print A Java array? Page views fully 220W+, unexpected ah, such a simple problem should have so many programmers have been troubled.

To recap the questioner’s question:

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?

If you have been or are struggling with this question, please come with me and let’s go through this question side by side hand in hand and find the best answer. Duang, Duang, Duang!

01. Why can’t you print it directly

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

String [] cmowers = {" silence ","ηŽ‹δΊŒ"," aN interesting programmer "}; System.out.println(cmowers);Copy the code

The program prints:

[Ljava.lang.String;@3d075dc0
Copy the code

[ljava.lang.String; specifies the Class name of an array of strings, followed by the hexadecimal hashCode at sign. To see why, look at the toString() method of the java.lang.object class.

public String toString(a) {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Copy the code

PS: 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.

public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
}
Copy the code

But is this really necessary? To define a single class for arrays is to gild the lily.

Use 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.

The first:

Arrays.asList(cmowers).stream().forEach(s -> System.out.println(s));
Copy the code

The second:

Stream.of(cmowers).forEach(System.out::println);
Copy the code

The third:

Arrays.stream(cmowers).forEach(System.out::println);
Copy the code

The printed result is shown below.

Silent King 2 an interesting programmerCopy the code

Yes, all three of these approaches are easy to do their job with, and look a little high and mighty, given the Stream and lambda expressions. But in my mind, they are not the most elegant way.

03. Use the for loop

Of course, if you don’t like the Stream method, you can use a for loop to print an array incidentally, or even for-each.

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

for (String s : cmowers) { System.out.println(s); }

But if you’re an ambitious programmer, it’s a little low. So what’s the most elegant way to do it?

Arrays.tostring ()

Arrays.tostring () converts any array to a string, including primitive and reference Arrays.


I don’t need to tell you much about the Arrays class, do I? I know what I mean, but I can’t resist saying that this class contains all sorts of handy ways to manipulate Arrays, so instead of Arrays, we should call it ArrayUtil.

There’s nothing more elegant than using the array.tostring () method to print Arrays, like, like, like the Mona Lisa smile.


Are you amused? Let’s take a look at the code example in a happy light.

String [] cmowers = {"Silence"."Two"."An interesting programmer."};
System.out.println(Arrays.toString(cmowers));
Copy the code

Program print results:

[Silence, Wang Er, an interesting programmer]Copy the code

Wow, print format is not too perfect, no more, no less! Exactly what we expect: [] indicates an array with dots and Spaces to split elements.

Take another look at the source code for the toString() method.

public static String toString(Object[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";
    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax)
            return b.append('] ').toString();
        b.append(","); }}Copy the code

1) If the array is null, return a NullPointerException string.

2) If array length is 0, return “[]” string. (I == iMax) (I == iMax) (I == iMax) (I == iMax) (I == iMax)

I == iMax (I < a.length); I == iMax (I == iMax)

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.

05, use,Arrays.deepToString()

If you need to print multi-dimensional Arrays, arrays.tostring () doesn’t work.

String[][] deepArray = new String[][] {{"Silence"."Two"}, {"An interesting programmer."}};
System.out.println(Arrays.toString(deepArray));
Copy the code

The output is as follows:

[[Ljava.lang.String;@7ba4f24f, [Ljava.lang.String;@3b9a45b3]
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[][] {{"Silence"."Two"}, {"An interesting programmer."}};
System.out.println(Arrays.deepToString(deepArray));
Copy the code

The output is as follows:

[silence, Wang Er], [a funny programmer]]Copy the code

Excellent!!!! The source code for deepToString() will not be analyzed in this article. If you are interested, take a look. (If you want excellence, you have to watch it.)

06, thanks

Well, readers, that’s all for this article. Can see here are the most excellent programmers, promotion pay is you πŸ‘. If you don’t like it and want to see more, I’ll recommend a few more.

Learning Java in 5 Minutes: Why Shouldn’t you Use Java primitive types?

Five minutes to learn Java: why ArrayIndexOutOfBoundsException will happen?

Five minutes to learn Java: why ArrayIndexOutOfBoundsException will happen?

Learning Java in 5 minutes: Is Java Passed by value or by reference?

NullPointerException: What are NullPointerExceptions?

Learning Java in 5 Minutes: How to compare Java strings?

Here comes the routine! If you are a hardcore reader, please don’t be stingy with the power of watching and forwarding in your hands. I like the feeling of being spoiled by big guys.

PS: Racking their brains recently came up with a magic propaganda word, we read it aloud:

Here is the “silent King two” public account, who cares who made a fortune, who cares who skin white.

I couldn’t help laughing (ha ha ha).