map calls the toString() method, and the returned string is spliced with spaces

Test code:


output:

    [123, 456]

After output, there will be a space in the header of the concatenated field.

Map toString() source code

public String toString() {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (! i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for (;;) {
            Entry<K,V> e = i.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key);
            sb.append('=');
            sb.append(value == this ? "(this Map)" : value);
            if (! i.hasNext())
                return sb.append('}').toString();
            sb.append(',').append(' ');
        }
    }

When splicing data in the source code, not only ',' but also spaces are added.

Solution:

    1. In the source code, remove "append(' ')". Modifying the source code is not recommended.

    2. Override toString(). Recommended to use.

    3. The string trim() can also be used to remove spaces for the concatenated data.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518063&siteId=291194637