1. 数组转字符串
import java.util.Arrays; public class Test02 { public static void main(String[] args){ String[] scores1 = new String[]{"10","20","30","40","50"}; String[] scores2 = {"10","20","30","40","50"}; // 数组转字符串 // 1.第一种方法 String str = Arrays.toString(scores1); System.out.println(str); // [10, 20, 30, 40, 50] // 2.第二种方法 String str2 = ""; for (int i = 0; i < scores1.length; i++) { str2 += scores1[i] + ","; } str2 = str2.substring(0, str2.length() - 1); System.out.println(str2); // 10,20,30,40,50 // 3.第三种方法(相比第二种,更推荐第三种) StringBuilder stringBuilder = new StringBuilder(); for (String score : scores1) { stringBuilder.append(score).append(","); } // String str3 = new StringBuilder(stringBuilder.substring(0, stringBuilder.length() - 1)).toString(); String str3 = stringBuilder.toString().substring(0, stringBuilder.length() - 1); System.out.println(str3); // 10,20,30,40,50 } }
2. 数组转ArrayList
import java.util.Arrays; public class Test02 { public static void main(String[] args){ // 数组转ArrayList String[] scores1 = new String[]{"10","20","30","40","50"}; // 1.第一种方法 ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(scores1)); System.out.println(arrayList); // [10, 20, 30, 40, 50] List<String> list = Arrays.asList(scores1); System.out.println(list); // [10, 20, 30, 40, 50] // 2.第二种方法 List<String> list2 = new ArrayList<String>(); for(String score : scores1){ list2.add(score); } } }
3. ArrayList转数组
import java.util.Arrays; public class Test02 { public static void main(String[] args){ // ArrayList转数组 List<String> list = new ArrayList(){{add("10");add("20");add("30");add("40");add("50");}}; System.out.println(list); // [10, 20, 30, 40, 50] //使用toArray(T[] a)方法 String[] arrayList = list.toArray(new String[0]); System.out.println(Arrays.toString(arrayList)); // [10, 20, 30, 40, 50] } }
4. ArrayList转字符串
public class Test02 { public static void main(String[] args){ // ArrayList转字符串 List<String> list = new ArrayList(){{add("10");add("20");add("30");add("40");add("50");}}; System.out.println(list); // [10, 20, 30, 40, 50] String str = list.toString(); System.out.println(str); // [10, 20, 30, 40, 50] } }
5. 字符串转数组
import java.util.Arrays; public class Test02 { public static void main(String[] args){ // 字符串转数组 String str = "10,20,30,40,50"; String[] strArr = str.split(","); System.out.println(Arrays.toString(strArr)); // [10, 20, 30, 40, 50] } }