java各类型的相互转化

一、List和数组的相互转化

  • 数组转化为List
        ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(array));
        List<Integer> list = Arrays.asList(array);
        //int 数组转化为list src为数组
        List<Integer> list = Arrays.stream( src ).boxed().collect(Collectors.toList());
      

这不是最好的,因为asList()返回的列表的大小是固定的。这里需要注意,对数组的修改也将影响list的值,ArrayList的本质实现就是这个数组。这种情况下,如果添加或删除列表中的元素,程序会抛出异常UnsupportedOperationException
我们也可以使用for循环,依次将值转化为list

  • List转化为数组
//使用toArray(T[] a)方法
 String[] array2 =(String[]) testList.toArray();

猜你喜欢

转载自blog.csdn.net/weixin_34349320/article/details/86998462