Java配列とList間の相互変換
16236 ワード
Java配列回転リストの3つの方式と比較
Listコレクションを配列に変換
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Java List
* @author BaiLiJun on 2019/10/25
*/
public class Test9 {
public static void main(String[] args) {
//simpleMethod();
//testArrayCastToListRight();
testArrayCastToListEfficient();
}
/**
* Collections.addAll(arrayList, strArray) , List,
* Collections.addAll() , , List ,
*/
private static void testArrayCastToListEfficient() {
String[] arr=new String[2];
ArrayList<String> list = new ArrayList<String>(arr.length);
Collections.addAll(list,arr);
list.add("1");
System.out.println("list = " + list);
}
/**
* ArrayList , Arrays.asList(strArray) java.util.Arrays.ArrayList java.util.ArrayList
*/
private static void testArrayCastToListRight() {
String[] arr=new String[2];
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr));
list.add("1");
System.out.println("list = " + list);
}
/**
* Arrays.asList(strArray) , List , List , , 。
*/
private static void simpleMethod() {
String[] arr=new String[2];
List<String> list = Arrays.asList(arr);
list.add("1");
System.out.println("list = " + list);
}
}
Listコレクションを配列に変換
import java.util.ArrayList;
/**
*
*
* @author BaiLiJun on 2019/10/25
*/
public class Test10 {
public static void main(String[] args) {
//method1();
//method2();
}
/**
* List
*/
private static void method1() {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
String[] arr = new String[list.size()];
for (int i = 0; i <list.size() ; i++) {
arr[i]=list.get(i);
}
for (String s : arr) {
System.out.println("s = " + s);
}
}
/**
* toArray() List , , :
* String[] array = (String[]) mlist.toArray();
* , java.lang.ClassCastException , ,
* java , List , List
*
* String[] array = mlist.toArray(new String[0]);
*/
private static void method2() {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
String[] array = list.toArray(new String[0]);
for (String s : array) {
System.out.println("s = " + s);
}
}
}