What do constructor type arguments mean when placed *before* the type? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What is the point of allowing type witnesses on all method calls?What are the rules for calling the superclass constructor?What does the explicit keyword mean?What does “static” mean in C?What is a clean, pythonic way to have multiple constructors in Python?What does 'synchronized' mean?What does map(&:name) mean in Ruby?What is a raw type and why shouldn't we use it?What does the star operator mean?What does “Could not find or load main class” mean?What is the difference between using constructor vs getInitialState in React / React Native?

Is there a verb for listening stealthily?

Why did Europeans not widely domesticate foxes?

Simulate round-robin tournament draw

Was Objective-C really a hindrance to Apple software development?

Why is arima in R one time step off?

Writing a T-SQL stored procedure to receive 4 numbers and insert them into a table

Is a self contained air-bullet cartridge feasible?

Why aren't road bicycle wheels tiny?

Did war bonds have better investment alternatives during WWII?

What's the difference between using dependency injection with a container and using a service locator?

What is ls Largest Number Formed by only moving two sticks in 508?

Test if all elements of a Foldable are the same

My admission is revoked after accepting the admission offer

Putting Ant-Man on house arrest

Does a Draconic Bloodline sorcerer's doubled proficiency bonus for Charisma checks against dragons apply to all dragon types or only the chosen one?

What do you call an IPA symbol that lacks a name (e.g. ɲ)?

Why doesn't the university give past final exams' answers?

Has a Nobel Peace laureate ever been accused of war crimes?

Does using the Inspiration rules for character defects encourage My Guy Syndrome?

SQL Server placement of master database files vs resource database files

Where/What are Arya's scars from?

Raising a bilingual kid. When should we introduce the majority language?

All ASCII characters with a given bit count

What is /etc/mtab in Linux?



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



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What is the point of allowing type witnesses on all method calls?What are the rules for calling the superclass constructor?What does the explicit keyword mean?What does “static” mean in C?What is a clean, pythonic way to have multiple constructors in Python?What does 'synchronized' mean?What does map(&:name) mean in Ruby?What is a raw type and why shouldn't we use it?What does the star operator mean?What does “Could not find or load main class” mean?What is the difference between using constructor vs getInitialState in React / React Native?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








123















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.










share|improve this question
























  • @NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

    – Ry-
    Apr 17 at 0:32


















123















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.










share|improve this question
























  • @NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

    – Ry-
    Apr 17 at 0:32














123












123








123


17






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.










share|improve this question
















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.







java generics syntax constructor generic-type-argument






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 17 at 0:25









user207421

265k26216365




265k26216365










asked Mar 25 at 2:55









Nathan AdamsNathan Adams

7331512




7331512












  • @NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

    – Ry-
    Apr 17 at 0:32


















  • @NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

    – Ry-
    Apr 17 at 0:32

















@NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

– Ry-
Apr 17 at 0:32






@NathanAdams: Stop adding “Java” back to the title in that spot, please – Stack Overflow uses tags.

– Ry-
Apr 17 at 0:32













2 Answers
2






active

oldest

votes


















137














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




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



  • Generics Constructor on CodesJava

  • JLS 15.9.3. Choosing the Constructor and its Arguments

  • JLS 15.12.2.1. Identify Potentially Applicable Methods

  • What is the point of allowing type witnesses on all method calls?





share|improve this answer

























  • But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

    – Jaspreet Jolly
    Mar 25 at 3:29






  • 3





    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)?

    – Slaw
    Mar 25 at 4:51







  • 4





    Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

    – Slaw
    Mar 25 at 5:03


















0














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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55330697%2fwhat-do-constructor-type-arguments-mean-when-placed-before-the-type%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    137














    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




    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



    • Generics Constructor on CodesJava

    • JLS 15.9.3. Choosing the Constructor and its Arguments

    • JLS 15.12.2.1. Identify Potentially Applicable Methods

    • What is the point of allowing type witnesses on all method calls?





    share|improve this answer

























    • But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

      – Jaspreet Jolly
      Mar 25 at 3:29






    • 3





      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)?

      – Slaw
      Mar 25 at 4:51







    • 4





      Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

      – Slaw
      Mar 25 at 5:03















    137














    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




    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



    • Generics Constructor on CodesJava

    • JLS 15.9.3. Choosing the Constructor and its Arguments

    • JLS 15.12.2.1. Identify Potentially Applicable Methods

    • What is the point of allowing type witnesses on all method calls?





    share|improve this answer

























    • But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

      – Jaspreet Jolly
      Mar 25 at 3:29






    • 3





      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)?

      – Slaw
      Mar 25 at 4:51







    • 4





      Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

      – Slaw
      Mar 25 at 5:03













    137












    137








    137







    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




    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



    • Generics Constructor on CodesJava

    • JLS 15.9.3. Choosing the Constructor and its Arguments

    • JLS 15.12.2.1. Identify Potentially Applicable Methods

    • What is the point of allowing type witnesses on all method calls?





    share|improve this answer















    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




    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



    • Generics Constructor on CodesJava

    • JLS 15.9.3. Choosing the Constructor and its Arguments

    • JLS 15.12.2.1. Identify Potentially Applicable Methods

    • What is the point of allowing type witnesses on all method calls?






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 25 at 10:27

























    answered Mar 25 at 3:13









    Ole V.V.Ole V.V.

    32.9k74259




    32.9k74259












    • But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

      – Jaspreet Jolly
      Mar 25 at 3:29






    • 3





      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)?

      – Slaw
      Mar 25 at 4:51







    • 4





      Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

      – Slaw
      Mar 25 at 5:03

















    • But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

      – Jaspreet Jolly
      Mar 25 at 3:29






    • 3





      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)?

      – Slaw
      Mar 25 at 4:51







    • 4





      Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

      – Slaw
      Mar 25 at 5:03
















    But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

    – Jaspreet Jolly
    Mar 25 at 3:29





    But how it is allowing 2 arguments <String, Long>.The list will allow storing which type of data?

    – Jaspreet Jolly
    Mar 25 at 3:29




    3




    3





    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)?

    – Slaw
    Mar 25 at 4:51






    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)?

    – Slaw
    Mar 25 at 4:51





    4




    4





    Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

    – Slaw
    Mar 25 at 5:03





    Hmm... maybe not a bug. See stackoverflow.com/questions/28014853/…

    – Slaw
    Mar 25 at 5:03













    0














    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.






    share|improve this answer



























      0














      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.






      share|improve this answer

























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 8:19









        svenmeiersvenmeier

        4,8961222




        4,8961222



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55330697%2fwhat-do-constructor-type-arguments-mean-when-placed-before-the-type%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bruad Bilen | Luke uk diar | NawigatsjuunCommonskategorii: BruadCommonskategorii: RunstükenWikiquote: Bruad

            What is the offset in a seaplane's hull?

            Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029