您的位置:首页 > 编程语言 > Java开发

编程技巧系列(4)Java数组转化成String

2016-04-29 11:32 411 查看
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();
}


3.最后自己的写了一个toString(array)

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: