简体   繁体   English

将Arrays.asList与int数组一起使用

[英]Using Arrays.asList with int array

Using java.util.Arrays.asList , why its shows different list size for int (Primitive type) and String array? 使用java.util.Arrays.asList ,为什么它显示int (Primitive类型)和String数组的不同列表大小?

a) With int array, whenever I execute following program the List size = 1 a)使用int数组,每当我执行以下程序时,List size = 1

public static void main(String[] args) {
        int ar[]=new int[]{1,2,3,4,5};
        List list=Arrays.asList(ar);
        System.out.println(list.size());

    }

b) But if i change from int array type to String array(like String ar[] = new String[]{"abc","klm","xyz","pqr"}; ) , then I am getting the list size as 4 which i think is correct. b)但是如果我从int数组类型更改为String数组(如String ar[] = new String[]{"abc","klm","xyz","pqr"}; ),那么我得到的列表大小为4,我认为是正确的。

PS : With Integer (Wrapper Class) array, then result is Fine, but i am not sure why in primitive int array, the list size is 1. Please explain. PS :使用Integer (Wrapper Class)数组,结果很好,但我不确定为什么在原始int数组中,列表大小为1.请解释。

List cannot hold primitive values because of java generics (see similar question ). 由于java泛型, List无法保存原始值(请参阅类似问题 )。 So when you call Arrays.asList(ar) the Arrays creates a list with exactly one item - the int array ar . 因此,当您调用Arrays.asList(ar) ,Arrays会创建一个只包含一个项目的列表 - int数组ar

EDIT: 编辑:

Result of Arrays.asList(ar) will be a List<int[]> , NOT List<int> and it will hold one item which is the array of int s: Arrays.asList(ar)结果将是List<int[]>NOT List<int> ,它将保存一个项目,即int的数组:

[ [1,2,3,4,5] ]

You cannot access the primitive int s from the list itself. 您无法从列表本身访问原语int You would have to access it like this: 您必须像这样访问它:

list.get(0).get(0) // returns 1
list.get(0).get(1) // returns 2
...

And I think that's not what you wanted. 而且我认为这不是你想要的。

List is a generic type, primitive types are not valid substitutes for the type parameter. List是泛型类型,原始类型不是type参数的有效替代。

So in your first example when you call Arrays.asList() with an int[] , the value for the type parameter will be int[] and not int , and it will return a list of int arrays. 因此,在您使用int[]调用Arrays.asList()第一个示例中,type参数的值将是int[]而不是int ,并且它将返回int数组的列表。 It will have only 1 element, the array itself. 它只有1个元素,数组本身。

The second case will be a List<String> , properly holding the 4 strings which you pass to it. 第二种情况是List<String> ,正确保存传递给它的4个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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