Why does Arrays.toString(values).trim() produce [bracketed text]?

半城伤御伤魂 提交于 2019-12-06 02:48:36

That is just the default formatting applied by the Arrays.toString(Object[]) method. If you want to skip the brackets you can build the string yourself, for example:

public static String toString(Object[] values)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.length; i++)
    {
        if (i != 0)
            sb.append(", ");
        sb.append(values[i].toString());
    }
    return sb.toString();
}

If your desired output is a list of values separated by commas (or something else), I like the approach with Guava's Joiner:

String valuesStr = Joiner.on(",").join(values)

Java's default implementation of the Arrays toString method is like that. You can create a class that extends it, specialized for what you want, and overwrite the toString method to make it generate a string of your liking, without the "[" "]"s, and with other restrictions of your liking and need.

I believe this is just how the implementation of Arrays.toString(Object[]) works, at least on the Sun JVM. If the array had multiple elements, you would see something like [foo, bar, baz].

Are you looking to basically get the same output, without the brackets? E.g. foo, bar, baz ? If so, then it should be pretty easy to write your own method.

I would suggest you use a string-builder or guava's joiner but if you want a quick fix,you can try this:

Arrays.toString(values).split("[\\[\\]]")[1];

Note: Use the above method only if the values themselves doesn't contain bracket's in them.

StringBuilder Implementaion:

 static String toString(Object ... strings)
 {
    if(strings.length==0)
        return "";
    StringBuilder sb=new StringBuilder();
    int last=strings.length-1;
    for(int i=0;i<last;i++)
        sb.append(strings[i]).append(",");
    sb.append(strings[last]);
    return sb.toString();
 }

UPDATE:

Using substring:

String s=(s=Arrays.toString(arr)).substring(1,s.length()-1); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!