Transformations between arrays, collections, strings in Java, and traversal with the enhanced for loop

Source: Internet
Author: User

Transformations between arrays, collections, strings in Java, and traversal with the enhanced for loop:

1 @Test2      Public voidTestDemo5 () {3arraylist<string> list =NewArraylist<string>();4List.add ("A-B 1");5List.add ("A-B 2");6List.add ("A-B 3");7List.add ("A-B 4");8       //  convert the collection to a string and separate it with ",":    9String join = Stringutils.join (list, ",");TenSystem.out.println ("join=" +join); One  A        // convert the set to an array:    -string[] str =Newstring[list.size ()]; -string[] arr =List.toarray (str); the       // enhanced for Loop traversal collection:     -          for(String name:arr) { -System.out.println ("name=" +name); -         } +       //  convert the array to a string:     -String s =arrays.tostring (arr); +System.out.println ("s=" +s); A      // convert the array to a collection:      atList<string> List2 =arrays.aslist (arr); -       // Strengthen for traversal collection:     -          for(String name2:list2) { -System.out.println ("name2=" +name2); -         } -  in}

2: Strengthen the format for the For loop:

Note: Using the enhanced for loop requires a pre-determined set or array not empty and then traversed, or an error occurs: null pointer exception

The use of the normal for loop is not necessary;

1 // data type: The type of data stored in a collection or array; 2 //   variable name: Can directly represent the elements in the collection or array; 3 for(data type variable name: Collection or array) {4    //  can be used directly inside the variable name:5     System.out.println ("Variable name =" + variable name); 6 }

Transformations between arrays, collections, strings in Java, and traversal with the enhanced for loop

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.