font color=#999AAA >Source:
Disclaimer: If I violate anyone's rights, please contact me and I will delete it
. Experts are welcome to spray me
Article Directory
ArrayList to one-dimensional array int[] —traversal/toArray()
//1. 遍历
ArrayList<Interger> list = new ArrayList<>();
list.add(1); list.add(2);
int[]arr = new int[list.size()];
int index= 0;
for(int a : list){
arr[index++] = a;
}
2. toArray()需要object做中转
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i< 10; i++) {
list.add(i);
}
Object[] arr = list.toArray();
int[] rett = new int[arr.length];
for(int i=0;i<arr.length;++i){
rett[i] = (int)arr[i];
}
System.out.println(Arrays.toString(rett));
ArrayList<Integer> to one-dimensional array int[] —toArray()
List<int[]> merged = new ArrayList<int[]>();
merged.toArray(new int[merged.size()][]);
ArrayList<ArrayList<Integer>> to two-dimensional array int[] [] did not find a way (because in the process of writing the program, the length of the two-dimensional array and the length of the one-dimensional array are uncertain, I feel ArrayList<ArrayList<Integer >> It will be convenient, but it is not easy to change back), so when this conversion is required in the program, it is recommended to use List<int[]> merged instead of ArrayList<ArrayList<Integer>>, which is very convenient
@Test
public void test5(){
int[] array = {1, 2, 5, 5, 5, 5, 6, 6, 7, 2, 9, 2};
/*int[]转list*/
//方法一:需要导入apache commons-lang3 jar
List<Integer> list = Arrays.asList(ArrayUtils.toObject(array));
//方法二:java8及以上版本
List<Integer> list1 = Arrays.stream(array).boxed().collect(Collectors.toList());
/*list转int[]*/
//方法一:
Integer[] intArr = list.toArray(new Integer[list.size()]);
//方法二:java8及以上版本
int[] intArr1 = list.stream().mapToInt(Integer::valueOf).toArray();
}