如何知道Stream.toArray(Book [] :: new);数组有多少个元素,"Book [] :: new"的实现在哪里 [英] How knows Stream.toArray(Book[]::new); how many elements the array has and where is the implementation of “Book[]::new”

查看:78
本文介绍了如何知道Stream.toArray(Book [] :: new);数组有多少个元素,"Book [] :: new"的实现在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解方法引用,但是我不知道如何使用此"Book [] :: new"它可以创建一个 具有正确数量的元素的数组.

I'm triying to understand method references and I don't know how with this "Book[]::new" it can create an array with the right number of elements.

Book[] arrayBook = stBooks.toArray(Book[]::new);

为了在使用第二个和第三个选项时创建数组,我必须指定一个功能接口 会收到一个Int并返回一个新的数组.

In order to create the array when I use the second and third option I have to specify a Functional Interface that Receive an Int and return a new Array.

但是,在第一个选项中,我不知道实现在哪里以及您在哪里指定数字或 具有数组的元素.我认为它为每个Stream元素创建了一个新的array元素 但是如果我理解得很好,则必须提供实现和"Book [] :: new"没有它.

But, in the first option I don't know where is the implementation and where you specify the number or elements that is going to have the array. I figure that it create a new array element for each Stream element but if I understand well you have to provide the implementation and "Book[]::new" doesn't have it.

Book book1 = new Book("ESDLA");
Book book2 = new Book("Harry Potter");
Stream<Book> stBooks = Stream.of(book1, book2);


1. Method References
Book[] arrayBook = stBooks.toArray(Book[]::new);

2. With Lambda Implementation
Book[] arrayBook1 = stBooks.toArray( (numElements) -> new Book[numElements] );

3. With Implementation
Book[] arrayBook2 = stBooks.toArray( new IntFunction<Book[]>() {

    @Override
    public Book[] apply(int numElements) {
        return new Book[numElements];
    }
});

推荐答案

如果方法引用表达式的格式为ArrayType::new,则将考虑单个概念方法.该方法具有单个int类型的参数,返回ArrayType,并且没有throws子句.如果n = 1,则这是唯一可能适用的方法;否则,没有可能适用的方法.

If the method reference expression has the form ArrayType::new, a single notional method is considered. The method has a single parameter of type int, returns the ArrayType, and has no throws clause. If n = 1, this is the only potentially applicable method; otherwise, there are no potentially applicable methods.

还有,:

如果形式为Type[]^k :: new(k≥1),则调用方法的主体与形式为new Type [ size ] []^k-1的数组创建表达式具有相同的效果,其中size是调用方法的单个参数. (符号[]^k表示k个括号对的序列.)

If the form is Type[]^k :: new (k ≥ 1), then the body of the invocation method has the same effect as an array creation expression of the form new Type [ size ] []^k-1, where size is the invocation method's single parameter. (The notation []^k indicates a sequence of k bracket pairs.)

因此,实现"是指您要查找的内容隐藏在Java编译器中的某处,因为它们都是编译器魔术".

So the "implementation" that you want to find is hidden somewhere in the Java compiler, as it's all "compiler magic".

这篇关于如何知道Stream.toArray(Book [] :: new);数组有多少个元素,"Book [] :: new"的实现在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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