Files
Knowledge/0 编程/java/Java中ArrayList、Integer[]和int[]的相互转换+42a39c68-1566-4a76-bfa8-bfa279d36a9c_23013RK75C_Jan-29-0936-2026_1.md

1.8 KiB

1. Integer[]转ArrayList

(1) 方法一:

利用Arrays工具类中的asList方法

Integer[] arr = {1,2,3};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(arr));

   
   
12
12

(2) 方法二:

利用Collections工具类中的addAll方法

Integer[] arr = {1,2,3};
ArrayList<Integer> list = new ArrayList<>(array.length);
Collections.addAll(list, arr);

   
   
123
123

(3) 注意: Java中集合只能存放引用数据类型,在使用asList或addAll方法时,被转换的数组必须是存放引用数据类型的数组,如果是基本数据类型数组请在转换前先把其转换为对应的包装类型数组,下面会介绍。

2. ArrayList转Integer[]
ArrayList<Integer> list = new ArrayList<>();
Integer[] arr = list.toArray(new Integer[0]);

   
   
12
12

二、Integer[]与int[]互转


1. Integer[]转int[]
Integer[] arr1 = {1,2,3};
int[] arr2 = Arrays.stream(arr1).mapToInt(Integer::valueOf).toArray();

   
   
12
12
2. int[]转Integer[]
int[] arr1 = {1,2,3};
Integer[] arr2 = Arrays.stream(arr1).boxed().toArray(Integer[]::new);

   
   
12
12

三、int[]与ArrayList的互转


1. int[]转ArrayList
int[] arr = {1,2,3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

   
   
12
12
2. ArrayList转int[]
ArrayList<Integer> list = new ArrayList<>();
int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();