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