1.首先我们来看java.util.Arrays的实现
/**
* Returns a string representation of the contents of the specified array. If the array contains other arrays as
* elements, they are converted to strings by the {@link Object#toString} method inherited from <tt>Object</tt>,
* which describes their <i>identities</i> rather than their contents.
*
* <p>
* The value returned by this method is equal to the value that would be returned by
* <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt> is <tt>null</tt>, in which case <tt>"null"</tt> is
* returned.
*
* @param a the array whose string representation to return
* @return a string representation of <tt>a</tt>
* @see #deepToString(Object[])
* @since 1.5
*/
public static String toString(Object[] a)
{
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++)
{
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
2. 我们看下org.springframework.util.ObjectUtils的实现
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(String.valueOf(array[i]));
}
sb.append(ARRAY_END);
return sb.toString();
}
public static String nullSafeToString(String[] array)
{
if (null == array)
{
return "null";
}
int length = array.length;
if (0 == length)
{
return "[]";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.append(i == 0 ? "[" : ", ").append(array[i]);
}
sb.append("]");
return sb.toString();
}