E.G. to create an ArrayList of Strings we have to do something like
List<String> list = new ArrayList<String>();
whereas it should be able to infer the parameter type for the constructor so that we only have to type
List<String> list = new ArrayList();
Why can't the type be infered in the same way that type parameters are infered for generic methods.
So, I can imagine that type inference was probably not supported because Java was aimed at programmers coming from C++, Pascal, or other mainstream languages that did not have it (principle of least surprise).
Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context.
Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.
This is a Java 7 improvement also known as the diamond operator. The syntax will be:
List<String> strings = new ArrayList<>();
The official proposal, accepted for inclusion in Project Coin is Improved Type Inference for Generic Instance Creation
According to Rémi Forax, the change is already in the mercurial repository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With