Java中ArrayList、Integer[]和int[]的相互转换
一、Integer[]与ArrayList的互转
1. Integer[]转ArrayList
(1) 方法一:
利用Arrays工具类中的asList方法
Integer[] arr = {1,2,3};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(arr));
- 1
- 2
(2) 方法二:
利用Collections工具类中的addAll方法
Integer[] arr = {1,2,3};
ArrayList<Integer> list = new ArrayList<>(array.length);
Collections.addAll(list, arr);
- 1
- 2
- 3
(3) 注意:
Java中集合只能存放引用数据类型,在使用asList或addAll方法时,被转换的数组必须是存放引用数据类型的数组,如果是基本数据类型数组请在转换前先把其转换为对应的包装类型数组,下面会介绍。
2. ArrayList转Integer[]
ArrayList<Integer> list = new ArrayList<>();
Integer[] arr = list.toArray(new Integer[0]);
- 1
- 2
二、Integer[]与int[]互转
1. Integer[]转int[]
Integer[] arr1 = {1,2,3};
int[] arr2 = Arrays.stream(arr1).mapToInt(Integer::valueOf).toArray();
- 1
- 2
2. int[]转Integer[]
int[] arr1 = {1,2,3};
Integer[] arr2 = Arrays.stream(arr1).boxed().toArray(Integer[]::new);
- 1
- 2
三、int[]与ArrayList的互转
1. int[]转ArrayList
int[] arr = {1,2,3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
- 1
- 2
2. ArrayList转int[]
ArrayList<Integer> list = new ArrayList<>();
int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();
- 1
- 2
本文详细介绍Java中Integer数组、int基本类型数组与ArrayList之间的相互转换方法。包括Integer[]与ArrayList的三种转换方式,Integer[]与int[]、int[]与ArrayList之间的转换实现。
681

被折叠的 条评论
为什么被折叠?



