The constructor reference is similar to the method reference, unlike the method name in the constructor reference is new. For example, Button::new represents the constructor reference for the Button class. For classes that have multiple constructors, choosing which constructor to use depends on the context. Suppose you have a list of strings, and you want to call the constructor of the button class to construct a list of buttons using the strings in the list, you can use the following expression:
List<string> labels = ....; stream<button> stream = Labels.stream (). Map (button::new); list<button> buttons = Stream.collect (Collectors.tolist ());
We will discuss the Stream,map and collect methods in detail later. But now, it's important that for each list element, the map method invokes the button (String) constructor. Although the button class has more than one constructor, the compiler infers from the context and picks a constructor with only one string argument.
You can use an array type to write a constructor reference. For example, Int[]::new is a constructor reference that contains a parameter, which is the length of the array. It is equivalent to the lambda expression x-new int[x]. The array constructor reference can be used to bypass a restriction in Java. In Java, you cannot construct an array of generic type T. The expression new T[n] is wrong because it will be erased as new object[n].
is a problem for developers who write APIs. For example, suppose we want to construct a set of buttons with a toarray () method that returns an object array in the stream interface:
object[] buttons = Stream.toarray ();
But that doesn't make us happy. The user wants a set of button objects, not a set of object objects. The Stream API solves this problem through a constructor reference. It allows button[]::new to be passed to the ToArray method:
button[] buttons = Stream.toarray (button[]::new);
The ToArray method calls the constructor to get an array of the correct type. It then populates and returns the array.
Java8 lambda expression (constructor reference)