Warning about converting Array to ArrayList
迷茫
迷茫 2017-06-12 09:25:17
0
2
727

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 arrayList = new ArrayList(Arrays.asList(arr)); } }
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all (2)
巴扎黑

asListis 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 whenasListis used.

Another problem is that evenInteger[]has a generic type mismatch problem withArrayListafter 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 Overflow

    世界只因有你
    // 声明数组 int[] arr = { 1, 10, 8 }; // 输出测试数组 System.out.println("测试的数组为:" + Arrays.toString(arr)); // 通过下角标访问元素,数组的下角标是从0开始的 System.out.println("通过数组的下角标访问元素,元素的下角标从0开始,下角标为0的元素是:" + arr[0]); // 将Array 转换成 Arraylist List ss = Arrays.asList(arr); ArrayList arrayList = new ArrayList();

    List cannot be automatically converted to ArrayList

    It is recommended to unify the data type, int[] arr = { 1, 10, 8 }; replaced by String[] arr = { "1", "10", "8" };

    // 声明数组 String[] arr = { "1", "10", "8" }; // 输出测试数组 System.out.println("测试的数组为:" + Arrays.toString(arr)); // 通过下角标访问元素,数组的下角标是从0开始的 System.out.println("通过数组的下角标访问元素,元素的下角标从0开始,下角标为0的元素是:" + arr[0]); // 将Array 转换成 Arraylist ArrayList arrayList = new ArrayList(Arrays.asList(arr));
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!