Using Arrays.asList array with int array
Using java.util.Arrays.asList
why does it show different list size for int
(primitive type) and String
array?
a) With an array int
, when I execute the following program, 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 go from array int
to array String
(for example String ar[] = new String[]{"abc","klm","xyz","pqr"};
) then I get a list size of 4 which I think is correct.
PS : with an array Integer
(Wrapper Class) then the result will be Fine, but I'm not sure why in a primitive array int
the list size is 1. Please explain.
source to share
List
cannot contain primitive values due to java generics (see similar question ). So when you call Arrays.asList(ar)
, Arrays creates a list with exactly one element - an array of int ar
.
EDIT:
The result Arrays.asList(ar)
will be List<int[]>
, NOT List<int>
and will contain one element, which is an array int
s:
[ [1,2,3,4,5] ]
You cannot access the primitive int
from the list itself. You will need to access it like this:
list.get(0).get(0) // returns 1
list.get(0).get(1) // returns 2
...
And I think that is not what you wanted.
source to share
List
is a typical type, primitive types are not valid type parameter substitutes.
So in the first example, when you call Arrays.asList()
with int[]
, the value for the type parameter will be int[]
, not int
, and it will return a list of int arrays. It will only have 1 element, the array itself.
The second case would be List<String>
by properly holding the 4 lines you pass to it.
source to share