当前位置:网站首页>01. Print array content (in string form)

01. Print array content (in string form)

2020-12-07 12:39:51 SSS soars thousands of miles

01. Array content printing (String form )

Source code display

//Arrays Class toString Method ( receive Long An array of types ), The type of parameter can be changed according to the situation 
public static String toString(long[] 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(", ");
        }
    }

Train of thought extraction

1. First step , The type of parameter is consistent with the type of argument , The return value type is String
2. The second step , Determine whether the array is empty ( The judgment that reference data types should perform ),
         If it is blank, return null,
         Step three is not empty ( no need else, Because of satisfaction if Conditional returns a value directly and ends the program )
3. The third step , Take variables imax( Random names ) Receive parameter array (a) Last position of ( The length of the array -1)
4. Step four , Judge imax( Last position in array ) Is it -1, if , Then return to []( Represents that the array length is 0)
5. Step five , Instantiate a StringBuilder class ( The splicing of array contents , More efficient StringBuffer high ),
         Its object name is set to stringBuilder
 Step six , by stringBuilder Add the left bracket "["(append)
 Step seven , Traversal array a,
      When i Is not the last position , by stringBuilder Add array element values (a[i]) And commas ( Add step by step )
      When i The position of the last one , Add the last element value of the array ,
      return stringBuffer Object call toString Result of method ( Before calling, you should append Right bracket above "]", One step )
   // Be careful : Whether it was used for the last one if conditional  if(i==imax)
  //      For the last time , There's no need to add commas ( Add reason for step by step )    

Scope of application

// The formal parameter is 8 An array of basic data types (short[],byte[],int[],float[],double[],char[],boolean[],long[])
// The method can be extended to ArrayList The printing of array contents 

版权声明
本文为[SSS soars thousands of miles]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207123635960m.html