Using Arrays.asList with int array

前端 未结 2 1700
星月不相逢
星月不相逢 2020-12-21 06:57

Using java.util.Arrays.asList, why its shows different list size for int (Primitive type) and String array?

a) With int

相关标签:
2条回答
  • 2020-12-21 07:30

    List cannot hold primitive values because of java generics (see similar question). So when you call Arrays.asList(ar) the Arrays creates a list with exactly one item - the int array 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 ints:

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

    You cannot access the primitive ints from the list itself. 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.

    0 讨论(0)
  • 2020-12-21 07:32

    List is a generic type, primitive types are not valid substitutes for the type parameter.

    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. It will have only 1 element, the array itself.

    The second case will be a List<String>, properly holding the 4 strings which you pass to it.

    0 讨论(0)
提交回复
热议问题