Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

java - Why does println(array) have strange output? ("[Ljava.lang.String;@3e25a5")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The toString() method of an array returns a String describing the identity of the array rather than its contents. That's because arrays don't override Object.toString(), whose documentation explains what you're seeing:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

To get a String representation of an array's contents, you can use Arrays.toString(Object[]).

The String returned by this method consists of each element's toString() representation, in the order they appear in the array and enclosed in square brackets ("[]"). Adjacent elements are separated by a comma and space (", ").

For example, calling this method on your array would result in the following String:

"[Einstein, , Newton, , Copernicus, , Kepler.]"

Note that the double commas and odd spacing are resulting because your array's element Strings already have punctuation and white space in them. Removing those:

String [] genius = {"Einstein", "Newton", "Copernicus", "Kepler"};

The method would then return this String:

"[Einstein, Newton, Copernicus, Kepler]"

It's important to notice that using this method doesn't give you any control over the formatting of the resulting String. It's nice for quickly checking the contents of an array, but is limited beyond that purpose. For example, what if you don't want those enclosing square brackets, or want to list each element line-by-line?

At this point you should start to see the value of implementing your own method to output the contents of your array in a way that's specific to your task. As others have suggested, practice this by using a for loop and building the new resulting String that you want to output.

You can find more information on for loops in this Java Tutorials article. In general, the Java Tutorials are great reading for a beginner and should accompany your course well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...