creatArrayList2方法,只用了一行代码。。
如果你反射牛逼,可以参考creatArrayList方法
- package test;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.LinkedList;
- import java.util.List;
- import org.junit.runners.model.InitializationError;
- public class ArrayToListFactory {
- public static String className;
- public static Class clazz;
- static{
- try {
- className="java.util.ArrayList";
- clazz=Class.forName(className);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
- public static void main(String[] args) {
- Integer[] arr=new Integer[]{1,2,3};
- List<Integer> list=creatArrayList(arr);
- for(int i=5;i<50;i++)
- list.add(i);
- System.out.println(list);
- }
- public static <T> List<T> creatArrayList(T[] arr) {
- final Object[] EMPTY_ELEMENTDATA = {};
- List<T> list=null;
- try {
- list=(List<T>) clazz.newInstance();
- Field sizeField= clazz.getDeclaredField("size");
- Field elementDataField= clazz.getDeclaredField("elementData");
- sizeField.setAccessible(true);
- elementDataField.setAccessible(true);
-
- Object[] arr2=null;
- int len=0;
- if ((len = arr.length) != 0) {
- if (arr.getClass() != Object[].class)
- arr2 = Arrays.copyOf(arr, len, Object[].class);
- } else {
- arr2 = EMPTY_ELEMENTDATA;
- }
- elementDataField.set(list, arr2);
- sizeField.set(list, len);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return list;
- }
- public static <T> List<T> creatArrayList2(T[] arr) {
- return new ArrayList<T>(Arrays.asList(arr));
- }
- }
复制代码
|