简体   繁体   中英

Android creates incorrect array list with method Arrays.asList

i have array

                    int[] pressed= new int[]{1,2,3};

                    List pS = Arrays.asList(pressed);

i expect what pS will contains array of integers with 1,2,3 values, but it contains array with one element which is a array of {1,2,3}

在此处输入图片说明

Try calling Arrays.asList(1,2,3); . The var-arg method asList() is treating your primitive array as one object and creates a list consisting of it. This shouldn't happen with reference types.

Alternatively declare pressed as Integer[] .

There is no way to use a primitive type as a generic in Java. If you can't change the int[] into an Integer[] , you will have to convert it by adding all the items yourself, like this:

public class ArrayUtil {

    public static ArrayList<Integer> asList(int[] array) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(array != null){
            for(int i=0; i<array.length; ++i){
                list.add(array[i]);
            }
        }
        return list;
    }

}

And to call it:

List pS = ArrayUtil.asList(pressed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM