3

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

a) With int array, whenever I execute following program the 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.

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.

Arun Kumar
  • 6,534
  • 13
  • 40
  • 67
  • 1
    Probably your compiler even gave you a raw type warning on `List`. Many IDEs will present a couple of useful fixes, one of them changing `List` to `List`. The latter pointing you towards the answers of "daerin" and "icza". – Hille Aug 25 '14 at 10:45

2 Answers2

5

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.

Community
  • 1
  • 1
daerin
  • 1,347
  • 1
  • 10
  • 17
  • So If the Arrays creates a list with exactly one item -the int array `ar` then how to traverse and access that primitive values from it using list? – Arun Kumar Aug 25 '14 at 11:55
  • Got it! It should be like `int ab[]=(int[]) list.get(0);` – Arun Kumar Aug 25 '14 at 13:08
  • Watch carefully! `list.get(0).get(0)` wouldn't be accessible directly here as last `get()` is undefined until and unless you **typecast** the whole statement to some other collection (that have `get` method) – Arun Kumar Aug 26 '14 at 04:36
1

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.

icza
  • 389,944
  • 63
  • 907
  • 827