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

徘徊边缘 提交于 2019-12-07 12:33:38

问题


Map<String, String[]> map = request.getParameterMap();
for (Entry<String, String[]> entry : map.entrySet())
{
    String name = entry.getKey();
    String[] values = entry.getValue();
    String valuesStr = Arrays.toString(values).trim();
    LOGGER.warn(valuesStr);

I'm trying to look at a request parameter value using the code above.

Why does Arrays.toString(values).trim(); bracket the parameter value so it looks like this:

[Georgio]

What's the best way to get the String here without the brackets?

If I do this:

String valuesStr = values[0].trim();

it seems there is a risk of losing subsequent values in the array.


回答1:


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();
}



回答2:


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)




回答3:


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.




回答4:


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.




回答5:


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); 


来源:https://stackoverflow.com/questions/3910507/why-does-arrays-tostringvalues-trim-produce-bracketed-text

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