java源碼之Arrays.toString()和Arrays.deepToString()

 

/**
 * 數組轉化成字符串
 * <p>
 * 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>
 * 返回指定數組的字符串,
 * 如果數組包含其他數組作爲元素,那麼這些元素將執行繼承自Object的toString方法,getClass().getName() + "@" Integer.toHexString(hashCode())的方式,而不是它們的內容。
 *
 * <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.
 * <p>
 * 該方法的返回值將和Arrays.asList(a).toString()方法返回值相同,除非a==null,這時方法的返回值是字符串"null",而後者返回null.
 *
 * @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";

    // 不用length==0來判斷空數組,因爲下面的代碼需要用到length-1
    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(", ");
    }
}

/**
 * 多維數組轉化成字符串(支持一維數或多維數組,一維基本類型數組需封裝)
 * <p>
 * <p>
 * Returns a string representation of the "deep contents" of the specified
 * array.  If the array contains other arrays as elements, the string
 * representation contains their contents and so on.  This method is
 * designed for converting multidimensional arrays to strings.
 * <p>
 * 該方法返回指定數組的深度內容字符串。
 * 如果數組的元素爲另一個數組,那麼返回的字符串將包含另一個數組的內容,以此類推,而不是另一個數組的引用。
 * 該方法是爲了把多維數組轉化爲字符串
 * <p>
 * The string representation consists of a list of the array's
 * elements, enclosed in square brackets (<tt>"[]"</tt>).  Adjacent
 * elements are separated by the characters <tt>", "</tt> (a comma
 * followed by a space).  Elements are converted to strings as by
 * <tt>String.valueOf(Object)</tt>, unless they are themselves
 * arrays.
 * <p>
 * 一系列數組元素將會被[]包含,相鄰元素用", "(英文,後有個空格)分隔的字符串輸出。元素將會調用String.value(Object)方法轉化成字符串,除非它們本身也是數組
 * <p>
 * If an element <tt>e</tt> is an array of a primitive type, it is
 * converted to a string as by invoking the appropriate overloading of
 * <tt>Arrays.toString(e)</tt>.  If an element <tt>e</tt> is an array of a
 * reference type, it is converted to a string as by invoking
 * this method recursively.
 * <p>
 * 如果元素爲基本類型數組,那麼會調用之前重載的Arrays.toString(e)方法轉化成字符串;如果元素爲引用類型數組,那麼將會遞歸調用以轉化成字符串。
 *
 * <p>To avoid infinite recursion, if the specified array contains itself
 * as an element, or contains an indirect reference to itself through one
 * or more levels of arrays, the self-reference is converted to the string
 * <tt>"[...]"</tt>.  For example, an array containing only a reference
 * to itself would be rendered as <tt>"[[...]]"</tt>.
 *
 * 爲了避免無限遞歸,當數組包含它自身作爲元素時,或者通過一層或多層數組間接的引用自身作爲元素,那麼這個數組將會以[...]的方式轉化成字符串。
 * 例如,一個數組僅包含自身作爲元素,那麼將會轉化成字符串[[...]]
 *
 * <p>This method returns <tt>"null"</tt> if the specified array
 * is <tt>null</tt>.
 * <p>
 * 如果數組爲null,將返回"null"
 *
 * @param a the array whose string representation to return
 * @return a string representation of <tt>a</tt>
 * @see #toString(Object[])
 * @since 1.5
 */
public static String deepToString(Object[] a) {
    if (a == null)
        return "null";

    int bufLen = 20 * a.length;
    if (a.length != 0 && bufLen <= 0)
        bufLen = Integer.MAX_VALUE;
    StringBuilder buf = new StringBuilder(bufLen);
    deepToString(a, buf, new HashSet<Object[]>());
    return buf.toString();
}

private static void deepToString(Object[] a, StringBuilder buf,
                                 Set<Object[]> dejaVu) {
    if (a == null) {
        buf.append("null");
        return;
    }
    int iMax = a.length - 1;
    if (iMax == -1) {
        buf.append("[]");
        return;
    }

    // 將多維數組的每一層數組都放到Set<Object[]>中,防止當數組自身作爲元素時無限遞歸調用
    dejaVu.add(a);
    buf.append('[');
    for (int i = 0; ; i++) {

        Object element = a[i];
        if (element == null) {
            buf.append("null");
        } else {
            Class<?> eClass = element.getClass();

            if (eClass.isArray()) {
                if (eClass == byte[].class)
                    buf.append(toString((byte[]) element));
                else if (eClass == short[].class)
                    buf.append(toString((short[]) element));
                else if (eClass == int[].class)
                    buf.append(toString((int[]) element));
                else if (eClass == long[].class)
                    buf.append(toString((long[]) element));
                else if (eClass == char[].class)
                    buf.append(toString((char[]) element));
                else if (eClass == float[].class)
                    buf.append(toString((float[]) element));
                else if (eClass == double[].class)
                    buf.append(toString((double[]) element));
                else if (eClass == boolean[].class)
                    buf.append(toString((boolean[]) element));
                else { // element is an array of object references
                    // 檢查Set中是否包含當前元素,如果包含,說明數組把自身作爲元素,直接輸出[...]
                    if (dejaVu.contains(element))
                        buf.append("[...]");
                    else
                        deepToString((Object[]) element, buf, dejaVu);
                }
            } else {  // element is non-null and not an array
                buf.append(element.toString());
            }
        }
        if (i == iMax)
            break;
        buf.append(", ");
    }
    buf.append(']');
    // todo 這裏爲何還要remove,爲了便於GC回收?
    dejaVu.remove(a);
}
發佈了2 篇原創文章 · 獲贊 0 · 訪問量 1023
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章