Java 8 Streams int和Integer [英] Java 8 Streams int and Integer

查看:64
本文介绍了Java 8 Streams int和Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是让Java 8弄脏了我,偶然发现了以下行为-

Was just getting my hands dirty with Java 8 and stumbled on a behaviour as below -

public static void main(String... args){
    System.out.println("[Start]");
    int[] ints = {1, 2, 3, 4};
    Stream.of(ints).forEach(i->System.out.println("Int : "+i));


    Integer[] integerNums = {1, 2, 3, 4};
    Stream.of(integerNums).forEach(i->System.out.println("Integer : "+i));

    System.out.println("[End]");
}

输出为:

[Start]
Int : [I@5acf9800
Integer : 1
Integer : 2
Integer : 3
Integer : 4
[End]

我希望代码在两种情况下都能打印所有int和Integer吗?任何对此的见解都将非常有帮助...

Whereas I was expecting the code to print all int's and Integer's in both the cases? Any insights on this would be greatly helpful...

推荐答案

泛型不适用于原始类型. Stream.of 方法声明为

Generics don't work with primitive types. The Stream.of method is declared as

static <T> Stream<T> of(T... values)

使用时

Stream.of(ints)

其中 ints 是一个 int [] ,Java没有看到许多 int 元素(原始类型),它看到了一个单个 int [] 元素(引用类型).因此,单个 int [] 被绑定为由 T ... values 表示的数组中的唯一元素.

where ints is an int[], Java doesn't see a number of int elements (primitive types), it sees a single int[] element (which is a reference type). So the single int[] is bound as the only element in the array represented by T... values.

因此, values 成为 int [] [] ,其每个元素都是 int [] ,其打印效果类似于

So values becomes an int[][] and each of its elements is an int[], which print like

[I@5acf9800

这篇关于Java 8 Streams int和Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆