【问题标题】:Reference method with array constructor [duplicate]带有数组构造函数的引用方法[重复]
【发布时间】:2016-12-21 15:03:02
【问题描述】:

我尝试在以下示例中使用带有表达式ArrayType[]::new 的引用方法:

public class Main
{
    public static void main(String[] args)
    {
        test1(3,A[]::new);
        test2(x -> new A[] { new A(), new A(), new A() });

        test3(A::new);
    }

    static void test1(int size, IntFunction<A[]> s)
    {
        System.out.println(Arrays.toString(s.apply(size)));
    }

    static void test2(IntFunction<A[]> s)
    {
        System.out.println(Arrays.toString(s.apply(3)));
    }

    static void test3(Supplier<A> s)
    {
        System.out.println(s.get());
    }
}

class A
{
    static int count = 0;
    int value = 0;

    A()
    {
        value = count++;
    }

    public String toString()
    {
        return Integer.toString(value);
    }
}

输出

[null, null, null]
[0, 1, 2]
3

但是我在方法test1 中得到的只是一个带有空元素的数组,表达式ArrayType[]::new 不应该创建一个具有指定大小的数组并为每个元素调用类A 的构造,就像发生的事情一样在方法test3中使用表达式Type::new时?

【问题讨论】:

    标签: java java-8 method-reference


    【解决方案1】:

    ArrayType[]::new 是对数组构造函数的方法引用。创建数组的实例时,元素被初始化为数组类型的默认值,引用类型的默认值为 null。

    正如new ArrayType[3] 产生一个包含3 个null 引用的数组一样,当s 是对数组构造函数的方法引用(即ArrayType[]::new)时调用s.apply(3) 也会产生一个包含3 个@987654327 的数组@引用。

    【讨论】:

    • 感谢您详细而清晰的解释。这是非常有帮助和可以理解的。
    • @NarutoBijuMode 不客气!
    • 作为附录,想要的操作可以通过test1(3, i -&gt; Stream.generate( A::new).limit(i).toArray(A[]::new));实现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多