Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

java - Using Arrays.asList with int array

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...