Since Java 7 it is allowed to use the diamond operator in order to avoid repeating the type argument. For example
List<String> myList = new ArrayList<String>();
becomes
List<String> myList = new ArrayList<>();
Why isn't the same notation allowed when using static method calls? For example when creating a SettableFuture I'd like to invoke
SettableFuture<String> myFuture = SettableFuture.<>create();
instead of
SettableFuture<String> myFuture = SettableFuture.<String>create();
I know it's possible to use the raw method call
SettableFuture<String> myFuture = SettableFuture.create();
but isn't this just the same as
List<String> myList = new ArrayList();
My question: Should I use the raw method call or repeat the type argument when calling generic static methods?
Java objects are created by means of the Constructor. Because this is the normal behavior, Java developers created the empty diamon as a sugar syntax feature.
A static method for object instanciation is not supposed to occur as frequent as the constructor. They are used for a lot of other stuff. Because of that, the syntax is not planned to detect if what you are trying to do is the creation of an object that needs a generic type.
EDIT:
I was wrong. There is syntax sugar also for types in static methods (leaving out the diamon) and create()
is more common than I thought.
My answer: I would prefer to leave out the diamon as the type is already specified in the variable and this way you avoid information redundancy in your code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments