Array、List相互変換

1895 ワード

配列をlistに変換するには、次の手順に従います.
package com.basic.object;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class ArrayToListTest {

	public static void main(String[] args) throws IOException {

		String[] strArray = { "string1", "string2", "string3" };
        // list
		List<String> strList = Arrays.asList(strArray);
		System.out.println(strList);
		for (String str : strList) {
			System.out.print(str+"、");
		}
		System.out.println(" ");
		for(int i=0;i<strList.size();i++){
			System.out.print(strList.get(i)+"、");
		}
	}
}

Listを配列に変換する:
package com.basic.object;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

public class ListToArrayTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<String> strList = new ArrayList<String>();
		strList.add("string1");
		strList.add("string2");
		strList.add("string3");
		System.out.println(strList);
		String[] strArray1 = strList.toArray(new String[]{});
		String[] strArray2 = strList.toArray(new String[strList.size()]);
		String[] strArray3 = (String[]) strList.toArray(new String[0]);
		
		System.out.println(ArrayUtils.toString(strArray1));
		System.out.println(ArrayUtils.toString(strArray2));
		System.out.println(ArrayUtils.toString(strArray3));
		System.out.println(" ");
		for(int i=0;i<strArray1.length;i++){
			System.out.print(strArray1[i]+"、");
		}

	}

}