1. First look at the case code as follows:
1 Packagecn.itcast_07;2 3 /*4 * Stitch the array into a string5 */6 Public classStringBufferTest2 {7 Public Static voidMain (string[] args) {8 //define an array9 int[] arr = {44, 33, 55, 11, 22 };Ten One //Defining features A //Mode 1: Use String to stitch the way -String S1 =arraytostring (arr); -System.out.println ("S1:" +s1); the - //Way 2: Use StringBuffer to do the stitching way -String s2 =arrayToString2 (arr); -System.out.println ("S2:" +S2); + } - + //the way to do stitching with StringBuffer A Public StaticString ArrayToString2 (int[] arr) { //Always use a StringBuffer string buffer object, saving memory overhead atStringBuffer SB =NewStringBuffer (); - -Sb.append ("["); - for(intx = 0; x < arr.length; X + +) { - if(x = = Arr.length-1) { - sb.append (arr[x]); in}Else { -Sb.append (Arr[x]). Append (","); to } + } -Sb.append ("]"); the * returnsb.tostring (); $ }Panax Notoginseng - //use String to stitch the way the Public StaticString arraytostring (int[] arr) { //open up multiple string constant memory, wasting overhead +String s = ""; A thes + = "["; + for(intx = 0; x < arr.length; X + +) { - if(x = = Arr.length-1) { $s + =Arr[x]; $}Else { -s + =Arr[x]; -s + = ","; the } - }Wuyis + = "]"; the - returns; Wu } -}
The results of the operation are as follows:
Java Basics Hardening the case of a 45:stringbuffer class to stitch an array into a string of a specified format