In the same way that method references are handles to existing methods, constructor reference are handles to existing constructors. Constructor references are created using syntax similar to that for method references, but with the method name replaced with the keyword new
. For example:
ArrayList::new
File::new
If the constructor is generic, type arguments can be explicitly declared before new
:
interface Factory<T> { T make(); }
Factory<ArrayList<String>> f1 = ArrayList::<String>new;
As with method references, the choice between overloaded constructors is made using the target type of the context. For example, the second line of the following code maps the Integer(String)
constructor on to each element of strList
(and then adds them all into a new collection using a collector):
List<String> strList = Arrays.asList("1","2","3");
List<Integer> intList = strList.stream().map(Integer::new).collect(Collectors.toList());
The map
method of Iterable
applies its argument (in this case the constructor for Integer
)
to each element of the receiver in turn, creating a new Iterable
to hold the results.
Leave a Reply