when i use Java 8 Stream.of primitive type, the result is confused

后端 未结 2 449
走了就别回头了
走了就别回头了 2020-12-11 07:11
    byte[] a = {1,2,3};
    System.out.println(Stream.of(a).count());

    Byte[] b = {1,2,3};
    System.out.println(Stream.of(b).count());

the re

2条回答
  •  时光取名叫无心
    2020-12-11 07:43

    For primitive arrays you should be using primitive streams, but unfortunately there is no ByteStream. If you change your byte[] to int[], you could write :

    int[] a = {1,2,3};
    System.out.println(IntStream.of(a).count());
    

    Otherwise you get a Stream whose single element is the input array, since both static Stream of(T t) and static Stream of(T... values) expect a reference type as the Stream element, so when you pass a primitive array, the only available reference type is the array itself.

    In your System.out.println(Stream.of(b).count()); case, b is an array of reference types, so static Stream of(T... values) is used to produce a Stream of 3 elements.

提交回复
热议问题