Learn to read source code of the program - an endless loop Magical

Now suppose you have an array of integers:

Integer [] = {20 is ARR, 20 is,. 4,. 4, 21 is,. 7}; // 2020 dated years. 4 of 5. 4. 7 Day 21 is when

How to spaces with a comma "," split the array elements and placed in the "[]" array element in order to obtain the following format string it?

  [20, 20, 4, 4, 21, 7]

Show you the code I wrote:

public static String toString(Object[] arr) {
    if (arr == null) {
         return "null";
    }
    StringBuilder result = new StringBuilder("[");
    for (int i = 0; i < arr.length; i++) {
        result.append(arr[i]);
        if (i < arr.length - 1) {
            result.append(", ");
        }
    }
    return result.append("]").toString();
}

Based on the current unit tests:

1. The length of the array should return to 0 []

@Test
public void printArray1() {
    Object[] arr = {};
    Assert.assertEquals("[]", toString(arr));
}

2. The array elements should be returned when said array element [20, 20, 4, 4, 21, 7]

@Test
public void printArray2() {
    Object[] arr = {20, 20, 4, 4, 21, 7};
    Assert.assertEquals("[20, 20, 4, 4, 21, 7]", toString(arr));
}

The method has been tested and is not a problem.

The JDK java.util.Arrays tools already have a way to realize this function, paste the following source code:

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(", ");
    }
}

Through the array are implemented by means of StringBuilder splicing elements, except as follows.

1. The length of the array is zero when handling

JDK is determined in the case where the array length is zero, then a direct return "[]"; I do not deal with this particular situation, but 0 when the loop is not executed for when indirectly controlled by the length of the array, this approach a bad place to be when the array length will create a StringBuilder object is 0.

2. Object array element if you want to convert to a String and then stitching

I direct the Object array elements are spliced ​​by a StringBuilder append (Object) method, but JDK's approach is to each element of the array Object calls the String.valueOf (Object) method and then converted to a String stitching, the benefits of doing so It may be better readability, but the code neat perspective unnecessary to do so, because the conversion of the append internal StringBuilder (Object) method itself would Object parameters String:

@Override
public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}

After the control element 3 and the last loop without splicing delimiter treatment

Conventional I i <arr.length controlled manner through the array, and special treatment explicitly last element (if (i <arr.length - 1)) where no splice separator; the practice of the JDK even more clever, with a for loop is infinite loop, return directly after traverse to the right bracket when the last element of the end of the stitching, like I do to avoid a final judgment in the for loop statement and the body of the loop, respectively, when the action element should be executed, execute more efficiently.

in conclusion

总体来看我的实现方式很常规,JDK 的实现显然更高明。

之前一直对死循环这一单纯听名字就可能产生灾难性问题的做法敬而远之,以为非特殊情况根本不会用到,通过此次比较发现,如果循环时需要处理特殊情况并在这种特殊情况时需要终止循环,则可以直接通过这种特殊情况控制循环,而无需单独作控制,这样可以显著提高程序执行效率。

综上,将 java.util.Arrays的方法作简单优化,去掉显示转换 Object 为 String 的方法并替换为 StringBuilder 的 append(Object)方法,得到如下方法:

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(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

 


 

我们的口号是:Learn from the best and be the best.

 

Guess you like

Origin www.cnblogs.com/weix-l/p/12635362.html