package com.sheting.basic.collection.list;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class ConvertListToArrayAndArrayToList {
public static void main(String[] args) {
convertListToArray_1();
convertArrayToList_1();
convertListToArray_2();
convertArrayToList_2();
convertArrayToList_3();
}
// ****Using plain Java****
public static void convertListToArray_1() {
List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
}
public static void convertArrayToList_1() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
List<Integer> targetList = Arrays.asList(sourceArray);
}
// **** Using Guava ****
public static void convertListToArray_2() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
int[] targetArray = Ints.toArray(sourceList);
// String 还是要是用Jdk转换
List<String> sourceList1 = Lists.newArrayList("j", "a", "v", "a");
String[] targetArray1 = sourceList1.toArray(new String[sourceList.size()]);
}
public static void convertArrayToList_2() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
List<Integer> targetList = Lists.newArrayList(sourceArray);
}
// **** Using Commons Collections
public static void convertArrayToList_3() {
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceArray);
}
}
Converting between an Array and a List in Java
最新推荐文章于 2023-08-05 01:13:28 发布