Java Basics Hardening the case of a 45:stringbuffer class to stitch an array into a string of a specified format

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.