Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive type and Wrapper type for Arrays.asList [duplicate]

Tags:

java

I have following simple test case

@Test
public void testArraysAsList() {
    Character[] chars1 = new Character[]{'a', 'b'};
    System.out.println(Arrays.asList(chars1).size());


    char[] chars2 = new char[]{'a', 'b'};
    System.out.println(Arrays.asList(chars2).size());

}

The result is: 2 1

I don't understand Arrays.asList(chars2), why Arrays.asList(char[]) makes a one size list,with the element being char[].

like image 771
Tom Avatar asked Nov 07 '17 08:11

Tom


1 Answers

As @Andy explains, generics only work with reference types. That means that List<char> is not allowed (so Arrays.asList cannot return List<char>). Instead Arrays.asList interprets its input as a single object and returns a list with that single element.

    Character[] chars1 = new Character[]{'a', 'b'};
    List<Character> list1 = Arrays.asList(chars1);

    char[] chars2 = new char[]{'a', 'b'};
    List<char[]> list2 = Arrays.asList(chars2);

Compare Arrays.asList(chars2) with this String example (where the input is also is a single element):

    String test = "test";
    List<String> asList = Arrays.asList(test);

Returns a list with size()==1

like image 62
Stefan Avatar answered Sep 28 '22 10:09

Stefan