Friday, November 9, 2018

Java 8 - Constructor References

Greetings!

This is same as the method references, except the method name is new.

Class::new


When we have multiple constructors which constructor will be selected? It depends on the context.


(firstName) -> new User(firstName) => User::new
(firstName, lastName) -> new User(firstName, lastName) => User::new


This can also be used with arrays with exact one parameter.

n -> new int[n]
int[]::new


This helps to create arrays with generic types.

Object[] array = stream.toArray();
User[] users = stream.toArray(User[]::new);


No comments:

Post a Comment