Array转换成ArrayList

来源:互联网 发布:经期助手软件 编辑:程序博客网 时间:2024/04/30 00:28


Array转换成ArrayList的问题,StackOverFlow上面有最佳答案,自己动手写了一下,发现结果并不像回答的那样。

关于这个问题的讨论,可以先看看这个链接,建议详细看问题后面的讨论。

http://stackoverflow.com/questions/157944/how-to-create-arraylist-arraylistt-from-array-t


@Test    public void testArrayAndArrayList(){        int[] a = {1,2,3,4};        System.out.println(Arrays.toString(a)); //[1, 2, 3, 4]        assertEquals(4, a.length);        List lista = new ArrayList(Arrays.asList(a));        assertEquals(1, lista.size());        System.out.println("Class type of first element in lista is : " + lista.get(0).getClass().getSimpleName()); //int[]        assertEquals(a.getClass(), lista.get(0).getClass());        Integer[] b = new Integer[]{new Integer(1), new Integer(2), new Integer(3), new Integer(4)};        System.out.println(Arrays.toString(b)); //[1, 2, 3, 4]        List listb = new ArrayList(Arrays.asList(b));        assertEquals(4, listb.size());        assertEquals(1,listb.get(0));    }


从上面的代码可以看到,使用Arrays.asList方法将基本类型数组转换成List之后,第一个元素就是数组本身,这并不是我们要的结果。


关于为什么要用new ArrayList(Arrays.asList(array)),stackoverflow上面的解释是这样的:


List<Element> list = Arrays.asList(array);

This will work fine. But some caveats:


The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList. Otherwise you'll get an UnsupportedOperationException.

The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.



那么如何将基本类型数组转换成ArrayList呢?

由于数组中的基本类型.不会进行自动装箱,需要手动完成装箱过程。


0 0
原创粉丝点击