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

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));
    }
}
迷茫
迷茫

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

reply all(2)
巴扎黑

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 is int[] in the question. If the data is defined as Integer[], it will be expanded as multiple variable parameters when asList is used.

Another problem is that even Integer[] has a generic type mismatch problem with ArrayList<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 Overflow

世界只因有你
    // 声明数组
        int[] arr = { 1, 10, 8 };
        // 输出测试数组
        System.out.println("测试的数组为:" + Arrays.toString(arr));

        // 通过下角标访问元素,数组的下角标是从0开始的
        System.out.println("通过数组的下角标访问元素,元素的下角标从0开始,下角标为0的元素是:" + arr[0]);

        // 将Array 转换成 Arraylist
        List<int[]> ss = Arrays.asList(arr);
        ArrayList<String> arrayList = new ArrayList<String>();

List<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" };

 // 声明数组
        String[] 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));
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!