Arrays.asList(word.toCharArray()) does not return a list?

  • A+
Category:Languages

I am trying to convert a String into a Stream<Character> and encountered this weird thing.

It seems word.toCharArray() returns an Array but when I try to convert it to a list by Arrays.asList(word.toCharArray()), it seems it failed (the output is a whole complete String).

What's going on here?

   @Test    public void testCharacterStream() {        characterStreamNew("HELLO");    }     private Stream<Character> characterStreamNew(String word) {       for(Character c: word.toCharArray()) {           out.println(c);       }       Arrays.asList(word.toCharArray()).stream()               .peek(out::println)               .forEachOrdered(out::println);       return null;    } 

And here is the output:

H E L L O HELLO HELLO 

 


What's going on here?

Here's the signature of Arrays.asList:

 public static <T> List<T> asList​(T... a) 

First observation is that T must be an object type. All Java type parameters are reference types.

Second observation is that a is a varargs parameter. That means that a can either be expressed as one or more T instances ... OR a T[].

To your example. It seems that you expect the following expression to produce a list of char or Character.

 Arrays.asList(word.toCharArray()) 

Firstly, List<char> is not a valid Java type, because char is not a reference type.

Secondly, List<Character> cannot be produced because that is not allowed by the signature. Lets try. If T is Character, then the substitution would be

   public static List<Character> asList(Character... a) 

but Character actually means Character[], and word.toCharArray() produces a char[]. (And the Java language will not convert char[] to Character[].)

In fact, what actually happens is that the T matches char[], and the result of Arrays.asList will be a List<char[]>. And the object that you get will be a list of size 1, with a single char[] element which contains all the characters of word.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: