Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 422
Hearen Avatar asked Dec 05 '25 21:12

Hearen


1 Answers

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 reference 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.

like image 144
Stephen C Avatar answered Dec 08 '25 12:12

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!