package com.demo.array;
import java.util.ArrayList;
import java.util.Arrays;
/**
* 关于数组的演示
*
* @author Captain
*
*/
public class ArrayDemo {
public static void main(String[] args) {
// 声明数组
int[] arr = { 1, 10, 8 };
// 输出测试数组
System.out.println("测试的数组为:" + Arrays.toString(arr));
// 通过下角标访问元素,数组的下角标是从0开始的
System.out.println("通过数组的下角标访问元素,元素的下角标从0开始,下角标为0的元素是:" + arr[0]);
// 将Array 转换成 Arraylist
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));
}
}
asList
is a generic function with variable parameters, so when an array is passed in, if the array is basic type data, it will be treated as an object, which isint[]
in the question. If the data is defined asInteger[]
, it will be expanded as multiple variable parameters whenasList
is used.Another problem is that even
Integer[]
has a generic type mismatch problem withArrayList<String>
after conversion. In Java8, you can use stream to convert it easily. In the previous Java version, you can use loop. Here is an answer on Stack OverflowList<int[]> cannot be automatically converted to ArrayList<String>
It is recommended to unify the data type, int[] arr = { 1, 10, 8 }; replaced by String[] arr = { "1", "10", "8" };