Now I am developing a simple project on Java.In that I include String Builder to append and print strings on console.When I am trying to append string array into string Builder,it prints object instead of array of strings on console.any one please tell whether my try is right or wrong.
3 Answers
- Add
Arrays.toString(yourArray)if you want to add the representation of yourStringarray. - If it's a multiple-dimension array (e.g. a
String[][]), then addArrays.deepToString(yourArray)to yourStringBuilder. - Adding the
arrayitself will add the defaultStringrepresentation. - Finally, if you need control over how you represent your
arraytoString, you'll need to iterate the elements yourself and add them to theStringBuilderin a customized format.
Edit
As a side-note, to make this work with arrays of custom Objects, you'll probably want to override the Object.toString method, otherwise your elements will be printed with the default String representation of Object (i.e. this).
6 Comments
Objects.Arrays.toString()? Because, am trying to append the elements from String[] to StringBuilder that has some elements already and I do not want to include a [ and ] in between.Apache Commons Lang StringUtils#join() very useful in this case. :)/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
Apache Commons Lang StringUtils#join(). is so cool. Hope this helps.