What do constructor type arguments mean when placed *before* the type?
Asked Answered
H

2

132

I've recently come across this unusual (to me) Java syntax...here's an example of it:

List list = new <String, Long>ArrayList();

Notice the positioning of the <String, Long> type arguments...it's not after the type as normal but before. I don't mind admitting I've never seen this syntax before. Also note there are 2 type arguments when ArrayList only has 1.

Does the positioning of the type arguments have the same meaning as putting them after the type? If not, what does the different positioning mean?

Why is it legal to have 2 type arguments when ArrayList only has 1?

I've searched the usual places, eg. Angelika Langer and on here but can't find any mention of this syntax anywhere apart from the grammar rules in the Java grammar file on the ANTLR project.

Hexameter answered 25/3, 2019 at 2:55 Comment(0)
M
146

Calling a generic constructor

This is unusual alright, but fully valid Java. To understand we need to know that a class may have a generic constructor, for example:

public class TypeWithGenericConstructor {

    public <T> TypeWithGenericConstructor(T arg) {
        // TODO Auto-generated constructor stub
    }
    
}

I suppose that more often than not when instantiating the class through the generic constructor we don’t need to make the type argument explicit. For example:

new TypeWithGenericConstructor(LocalDate.now(ZoneId.systemDefault()));

Now T is clearly LocalDate. However there may be cases where Java cannot infer (deduce) the type argument. Then we supply it explicitly using the syntax from your question:

new <LocalDate>TypeWithGenericConstructor(null);

Of course we may also supply it even though it is not necessary if we think it helps readability or for whatever reason:

new <LocalDate>TypeWithGenericConstructor(LocalDate.now(ZoneId.systemDefault()));

In your question you seem to be calling the java.util.ArrayList constructor. That constructor is not generic (only the ArrayList class as a whole is, that’s something else). For why Java allows you to supply type arguments in the call when they are not used, see my edit below. My Eclipse gives me a warning:

Unused type arguments for the non generic constructor ArrayList() of type ArrayList; it should not be parameterized with arguments <String, Long>

But it’s not an error, and the program runs fine (I additionally get warnings about missing type arguments for List and ArrayList, but that again is a different story).

Generic class versus generic constructor

Does the positioning of the type arguments have the same meaning as putting them after the type? If not, what does the different positioning mean?

No, it’s different. The usual type argument/s after the type (ArrayList<Integer>()) are for the generic class. The type arguments before are for the constructor.

The two forms may also be combined:

List<Integer> list = new <String, Long>ArrayList<Integer>();

I would consider this a bit more correct since we can now see that the list stores Integer objects (I’d still prefer to leave out the meaningless <String, Long>, of course).

Why is it legal to have 2 type arguments when ArrayList only has 1?

First, if you supply type arguments before the type, you should supply the correct number for the constructor, not for the class, so it hasn’t got anything to do with how many type arguments the ArrayList class has got. That really means that in this case you shouldn’t supply any since the constructor doesn’t take type arguments (it’s not generic). When you supply some anyway, they are ignored, which is why it doesn’t matter how many or how few you supply.

Why are meaningless type arguments allowed?

Edit with thanks to @Slaw for the link: Java allows type arguments on all method calls. If the called method is generic, the type arguments are used; if not, they are ignored. For example:

int length = "My string".<List>length();

Yes, it’s absurd. The Java Language Specification (JLS) gives this justification in subsection 15.12.2.1:

This rule stems from issues of compatibility and principles of substitutability. Since interfaces or superclasses may be generified independently of their subtypes, we may override a generic method with a non-generic one. However, the overriding (non-generic) method must be applicable to calls to the generic method, including calls that explicitly pass type arguments. Otherwise the subtype would not be substitutable for its generified supertype.

The argument doesn’t hold for constructors since they cannot be directly overridden. But I suppose they wanted to have the same rule in order not to make the already complicated rules too complicated. In any case, section 15.9.3 on instantiation and new more than once refers to 15.12.2.

Links

Machine answered 25/3, 2019 at 3:13 Comment(3)
But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?Blok
What's interesting to me, and sorry if I missed you already mentioning/implying this, is if the constructor (or method) is generic, having the incorrect number of type arguments results in a compilation error—at least for me in OpenJDK 12. For example, if you have class Test { <T> Test() {} } then calling new <String, Long>Test() is an error. Yet when the constructor (or method) is not generic it lets you add type arguments to your hearts desire... maybe this should be considered a bug (if not in the compiler then in the specification)?Revest
Hmm... maybe not a bug. See #28015353Revest
P
1

Apparently you can prefix any non-generic method/constructor with any generic parameter you like:

new <Long>String();
Thread.currentThread().<Long>getName();

The compiler doesn't care, because it doesn't have to match theses type arguments to actual generic parameters.

As soon as the compiler has to check the arguments, it complains about a mismatch:

Collections.<String, Long>singleton("A"); // does not compile

Seems like a compiler bug to me.

Palindrome answered 25/3, 2019 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.