开发者

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

开发者 https://www.devze.com 2023-01-19 19:19 出处:网络
Map<String, String[]> map = request.getParameterMap(); for (Entry<String, String[]> entry : map.entrySet())
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 wit开发者_如何转开发hout the brackets?

If I do this:

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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消