Uses of T extends U?Meaning of <T, U extends T> in java function declarationGenerics parameter extends another parameter on java method“implements Runnable” vs “extends Thread” in JavaWhat is PECS (Producer Extends Consumer Super)?Difference between <? super T> and <? extends T> in JavaJava nested self referential genericWhy is it not possible to call List<Number> not with List<Integer> even if Integer extends Number?Java Class extends Abstract class but must have static methodJava: Within abstract class create method that gets name of extending classHow do I make a class extending another extended class work with generic collections?Understanding Java Generics <T extends Class> and <? extends Class>In Java, why can I only restrict collection parameters using generics?

How do I calculate APR from monthly instalments?

What is the advantage of carrying a tripod and ND-filters when you could use image stacking instead?

Movie where a boy is transported into the future by an alien spaceship

Is there any word or phrase for negative bearing?

Bug using breqn and babel

How do I write "Show, Don't Tell" as an Asperger?

How can this map be coloured using four colours?

How do photons get into the eyes?

Can a magnetic field of an object be stronger than its gravity?

Aligning object in a commutative diagram

Why don't B747s start takeoffs with full throttle?

How can Iron Man's suit withstand this?

What is the purpose of building foundations?

Does the first version of Linux developed by Linus Torvalds have a GUI?

How to make thick Asian sauces?

Secure offsite backup, even in the case of hacker root access

How to supress loops in a digraph?

Avoiding cliches when writing gods

On the Twin Paradox Again

Company did not petition for visa in a timely manner. Is asking me to work from overseas, but wants me to take a paycut

Reading two lines in piano

Pronoun introduced before its antecedent

Implement Homestuck's Catenative Doomsday Dice Cascader

Why is quantum entanglement surprising?



Uses of T extends U?


Meaning of <T, U extends T> in java function declarationGenerics parameter extends another parameter on java method“implements Runnable” vs “extends Thread” in JavaWhat is PECS (Producer Extends Consumer Super)?Difference between <? super T> and <? extends T> in JavaJava nested self referential genericWhy is it not possible to call List<Number> not with List<Integer> even if Integer extends Number?Java Class extends Abstract class but must have static methodJava: Within abstract class create method that gets name of extending classHow do I make a class extending another extended class work with generic collections?Understanding Java Generics <T extends Class> and <? extends Class>In Java, why can I only restrict collection parameters using generics?






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








15















Lately I encountered a method defined similar to this and I don't exactly understand its usage:



public static <T, U extends T> T foo(U u) ... 


A sample use could be like this:



// Baz is just the containing class of foo()
Number n = Baz.foo(1);


Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:



public static <T> T bar(T t) ... 


If I call it like this:



Number n = Baz.bar(2);


The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)



I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.










share|improve this question

















  • 8





    Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

    – Thilo
    May 27 at 11:16











  • @Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

    – Lino
    May 27 at 11:24






  • 1





    That's different. It doesn't return T, it returns Something<T>.

    – RealSkeptic
    May 27 at 11:27











  • @RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

    – Lino
    May 27 at 11:34







  • 1





    @Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

    – MC Emperor
    May 27 at 11:57


















15















Lately I encountered a method defined similar to this and I don't exactly understand its usage:



public static <T, U extends T> T foo(U u) ... 


A sample use could be like this:



// Baz is just the containing class of foo()
Number n = Baz.foo(1);


Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:



public static <T> T bar(T t) ... 


If I call it like this:



Number n = Baz.bar(2);


The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)



I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.










share|improve this question

















  • 8





    Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

    – Thilo
    May 27 at 11:16











  • @Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

    – Lino
    May 27 at 11:24






  • 1





    That's different. It doesn't return T, it returns Something<T>.

    – RealSkeptic
    May 27 at 11:27











  • @RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

    – Lino
    May 27 at 11:34







  • 1





    @Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

    – MC Emperor
    May 27 at 11:57














15












15








15


2






Lately I encountered a method defined similar to this and I don't exactly understand its usage:



public static <T, U extends T> T foo(U u) ... 


A sample use could be like this:



// Baz is just the containing class of foo()
Number n = Baz.foo(1);


Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:



public static <T> T bar(T t) ... 


If I call it like this:



Number n = Baz.bar(2);


The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)



I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.










share|improve this question














Lately I encountered a method defined similar to this and I don't exactly understand its usage:



public static <T, U extends T> T foo(U u) ... 


A sample use could be like this:



// Baz is just the containing class of foo()
Number n = Baz.foo(1);


Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:



public static <T> T bar(T t) ... 


If I call it like this:



Number n = Baz.bar(2);


The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)



I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.







java generics






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 27 at 11:03









LinoLino

13.1k32850




13.1k32850







  • 8





    Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

    – Thilo
    May 27 at 11:16











  • @Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

    – Lino
    May 27 at 11:24






  • 1





    That's different. It doesn't return T, it returns Something<T>.

    – RealSkeptic
    May 27 at 11:27











  • @RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

    – Lino
    May 27 at 11:34







  • 1





    @Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

    – MC Emperor
    May 27 at 11:57













  • 8





    Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

    – Thilo
    May 27 at 11:16











  • @Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

    – Lino
    May 27 at 11:24






  • 1





    That's different. It doesn't return T, it returns Something<T>.

    – RealSkeptic
    May 27 at 11:27











  • @RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

    – Lino
    May 27 at 11:34







  • 1





    @Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

    – MC Emperor
    May 27 at 11:57








8




8





Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

– Thilo
May 27 at 11:16





Maybe your simplified example skipped over an aspect where this extra T makes sense. Can you link/include the real signature?

– Thilo
May 27 at 11:16













@Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

– Lino
May 27 at 11:24





@Thilo I don't have a real code sample. I encountered it when seeing this question. The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate"). But that still doesn't make much sense as with a single generic parameter the result would be same. Pass in an Object and receive an Object.

– Lino
May 27 at 11:24




1




1





That's different. It doesn't return T, it returns Something<T>.

– RealSkeptic
May 27 at 11:27





That's different. It doesn't return T, it returns Something<T>.

– RealSkeptic
May 27 at 11:27













@RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

– Lino
May 27 at 11:34






@RealSkeptic heck! You're right, in that case it does make sense (I think). Because generics are not implicitly polymorphic (I think that's how it's called). String extends Object but Something<String> does not extends Something<Object>

– Lino
May 27 at 11:34





1




1





@Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

– MC Emperor
May 27 at 11:57






@Lino Yeah, but I'm still not convinced. I don't think your specific of <T, U extends T> T foo(U u) is any other than drop the U and just replacing it with T. The example provided by Marco13 is not entirely the same as your example: it is using List<U> instead of simply U. I agree that in the context of parameterized types (Something<U>) it'll make sense, but I doubt that it is also the case in the context of a type parameter (U).

– MC Emperor
May 27 at 11:57













4 Answers
4






active

oldest

votes


















9














I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.



(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)



This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.




A small update:



Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.



In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.




An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:



import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod
public static void main(String[] args)

Integer integer = null;
Number number = null;

List<Number> numberList = null;
List<Integer> integerList = null;

// Always works:
integer = fooTrivial(integer);
number = fooTrivial(number);
number = fooTrivial(integer);

numberList = withList(numberList);
//numberList = withList(integerList); // Does not work

// Both work:
numberList = withListAndBound(numberList);
numberList = withListAndBound(integerList);


public static <T, U extends T> T fooTrivial(U u)
return u;


public static <T, U extends T> List<T> withListAndBound(List<U> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;


public static <T> List<T> withList(List<T> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;





(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)






share|improve this answer

























  • You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











  • In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

    – MC Emperor
    May 27 at 11:52











  • @MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

    – Lino
    May 27 at 11:54







  • 5





    @Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

    – Marco13
    May 27 at 11:57


















3














This is handy when you want to return a super type; exactly like you showed in your example.



You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.



This should be an example of what I mean actually. Suppose a very simple class like:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public <U super T> U whenNull(U whenNull)
return t == null ? whenNull : t;




Method whenNull as it is defined would not compile, as U super T is not allowed in java.



Instead you could add another type parameter and invert the types:



static class Holder<U, T extends U> 

private final T t;

public Holder(T t)
this.t = t;


public U whenNull(U whenNull)
return t == null ? whenNull : t;




And usage would be:



Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);


this allows to return a super type; but it looks very weird. We have added another type in the class declaration.



We could resort to:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder)
return holder.t == null ? whenNull : holder.t;




or even make this method static.



For an existing limitation, you could try to do:



Optional.ofNullable(<SomeSubTypeThatIsNull>)
.orElse(<SomeSuperType>)





share|improve this answer




















  • 7





    But you wouldn't actually need to, because U is assignable to T anyway.

    – RealSkeptic
    May 27 at 11:25











  • I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











  • I think he is right, gonna update my answer accordingly.

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00


















2














The first method



public static <T, U extends T> T foo(U u) ... 


means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.



With your second example



public static <T> T bar(T t) ... 


bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.






share|improve this answer


















  • 1





    But the object it returns can be assignable or usable in any context that requires its supertype.

    – RealSkeptic
    May 27 at 11:26











  • This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

    – Thomas Kainrad
    May 27 at 11:37











  • @ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











  • I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

    – Thomas Kainrad
    May 27 at 11:44






  • 2





    From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

    – Thomas Kainrad
    May 27 at 12:00


















2














My first thought was: heck,



Number n = Baz.bar(2);


would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!



Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!



Something like



class B 
class C extends B


now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.



In other words: the U extends T allows you to return instances of B and C. T alone: only C!



But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!



So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.






share|improve this answer




















  • 1





    @RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

    – GhostCat
    May 27 at 11:37






  • 1





    No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





    @RealSkeptic I meant Optional::orElse, my bad, which does return a T

    – Eugene
    May 27 at 11:55






  • 1





    @RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

    – Eugene
    May 27 at 12:15






  • 1





    for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

    – Eugene
    May 27 at 12:16











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%2f56324835%2fuses-of-t-extends-u%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























4 Answers
4






active

oldest

votes








4 Answers
4






active

oldest

votes









active

oldest

votes






active

oldest

votes









9














I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.



(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)



This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.




A small update:



Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.



In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.




An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:



import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod
public static void main(String[] args)

Integer integer = null;
Number number = null;

List<Number> numberList = null;
List<Integer> integerList = null;

// Always works:
integer = fooTrivial(integer);
number = fooTrivial(number);
number = fooTrivial(integer);

numberList = withList(numberList);
//numberList = withList(integerList); // Does not work

// Both work:
numberList = withListAndBound(numberList);
numberList = withListAndBound(integerList);


public static <T, U extends T> T fooTrivial(U u)
return u;


public static <T, U extends T> List<T> withListAndBound(List<U> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;


public static <T> List<T> withList(List<T> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;





(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)






share|improve this answer

























  • You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











  • In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

    – MC Emperor
    May 27 at 11:52











  • @MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

    – Lino
    May 27 at 11:54







  • 5





    @Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

    – Marco13
    May 27 at 11:57















9














I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.



(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)



This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.




A small update:



Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.



In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.




An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:



import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod
public static void main(String[] args)

Integer integer = null;
Number number = null;

List<Number> numberList = null;
List<Integer> integerList = null;

// Always works:
integer = fooTrivial(integer);
number = fooTrivial(number);
number = fooTrivial(integer);

numberList = withList(numberList);
//numberList = withList(integerList); // Does not work

// Both work:
numberList = withListAndBound(numberList);
numberList = withListAndBound(integerList);


public static <T, U extends T> T fooTrivial(U u)
return u;


public static <T, U extends T> List<T> withListAndBound(List<U> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;


public static <T> List<T> withList(List<T> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;





(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)






share|improve this answer

























  • You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











  • In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

    – MC Emperor
    May 27 at 11:52











  • @MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

    – Lino
    May 27 at 11:54







  • 5





    @Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

    – Marco13
    May 27 at 11:57













9












9








9







I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.



(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)



This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.




A small update:



Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.



In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.




An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:



import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod
public static void main(String[] args)

Integer integer = null;
Number number = null;

List<Number> numberList = null;
List<Integer> integerList = null;

// Always works:
integer = fooTrivial(integer);
number = fooTrivial(number);
number = fooTrivial(integer);

numberList = withList(numberList);
//numberList = withList(integerList); // Does not work

// Both work:
numberList = withListAndBound(numberList);
numberList = withListAndBound(integerList);


public static <T, U extends T> T fooTrivial(U u)
return u;


public static <T, U extends T> List<T> withListAndBound(List<U> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;


public static <T> List<T> withList(List<T> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;





(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)






share|improve this answer















I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.



(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)



This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.




A small update:



Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.



In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.




An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:



import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod
public static void main(String[] args)

Integer integer = null;
Number number = null;

List<Number> numberList = null;
List<Integer> integerList = null;

// Always works:
integer = fooTrivial(integer);
number = fooTrivial(number);
number = fooTrivial(integer);

numberList = withList(numberList);
//numberList = withList(integerList); // Does not work

// Both work:
numberList = withListAndBound(numberList);
numberList = withListAndBound(integerList);


public static <T, U extends T> T fooTrivial(U u)
return u;


public static <T, U extends T> List<T> withListAndBound(List<U> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;


public static <T> List<T> withList(List<T> u)
List<T> result = new ArrayList<T>();
result.add(u.get(0));
return result;





(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)







share|improve this answer














share|improve this answer



share|improve this answer








edited May 27 at 12:07

























answered May 27 at 11:40









Marco13Marco13

43.9k861114




43.9k861114












  • You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











  • In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

    – MC Emperor
    May 27 at 11:52











  • @MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

    – Lino
    May 27 at 11:54







  • 5





    @Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

    – Marco13
    May 27 at 11:57

















  • You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











  • In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

    – MC Emperor
    May 27 at 11:52











  • @MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

    – Lino
    May 27 at 11:54







  • 5





    @Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

    – Marco13
    May 27 at 11:57
















You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

– Lino
May 27 at 11:48





You're right. In this case it kind of makes sense. Though one could also just write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

– Lino
May 27 at 11:48













In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

– MC Emperor
May 27 at 11:52





In this case it does make sense, but in the case of OP's example, where the received parameter is of type U and not of type Something<U>, I cannot imagine a case where it actually makes a difference.

– MC Emperor
May 27 at 11:52













@MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

– Lino
May 27 at 11:54






@MCEmperor actually I kind of missinterpreted the code where I've seen it. In that question they return a parameterized class AutoBean<T> instead of simple T. So it does make sense I guess

– Lino
May 27 at 11:54





5




5





@Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

– Marco13
May 27 at 11:57





@Lino Indeed, instead of such a U extends T, one can often (and could in this example) use ? extends T in the signature. A case where this is not possible would be, for example, List<T> copyAndAdd(List<U> us, U anotherU) where the U has to be known for the second parameter.

– Marco13
May 27 at 11:57













3














This is handy when you want to return a super type; exactly like you showed in your example.



You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.



This should be an example of what I mean actually. Suppose a very simple class like:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public <U super T> U whenNull(U whenNull)
return t == null ? whenNull : t;




Method whenNull as it is defined would not compile, as U super T is not allowed in java.



Instead you could add another type parameter and invert the types:



static class Holder<U, T extends U> 

private final T t;

public Holder(T t)
this.t = t;


public U whenNull(U whenNull)
return t == null ? whenNull : t;




And usage would be:



Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);


this allows to return a super type; but it looks very weird. We have added another type in the class declaration.



We could resort to:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder)
return holder.t == null ? whenNull : holder.t;




or even make this method static.



For an existing limitation, you could try to do:



Optional.ofNullable(<SomeSubTypeThatIsNull>)
.orElse(<SomeSuperType>)





share|improve this answer




















  • 7





    But you wouldn't actually need to, because U is assignable to T anyway.

    – RealSkeptic
    May 27 at 11:25











  • I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











  • I think he is right, gonna update my answer accordingly.

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00















3














This is handy when you want to return a super type; exactly like you showed in your example.



You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.



This should be an example of what I mean actually. Suppose a very simple class like:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public <U super T> U whenNull(U whenNull)
return t == null ? whenNull : t;




Method whenNull as it is defined would not compile, as U super T is not allowed in java.



Instead you could add another type parameter and invert the types:



static class Holder<U, T extends U> 

private final T t;

public Holder(T t)
this.t = t;


public U whenNull(U whenNull)
return t == null ? whenNull : t;




And usage would be:



Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);


this allows to return a super type; but it looks very weird. We have added another type in the class declaration.



We could resort to:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder)
return holder.t == null ? whenNull : holder.t;




or even make this method static.



For an existing limitation, you could try to do:



Optional.ofNullable(<SomeSubTypeThatIsNull>)
.orElse(<SomeSuperType>)





share|improve this answer




















  • 7





    But you wouldn't actually need to, because U is assignable to T anyway.

    – RealSkeptic
    May 27 at 11:25











  • I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











  • I think he is right, gonna update my answer accordingly.

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00













3












3








3







This is handy when you want to return a super type; exactly like you showed in your example.



You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.



This should be an example of what I mean actually. Suppose a very simple class like:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public <U super T> U whenNull(U whenNull)
return t == null ? whenNull : t;




Method whenNull as it is defined would not compile, as U super T is not allowed in java.



Instead you could add another type parameter and invert the types:



static class Holder<U, T extends U> 

private final T t;

public Holder(T t)
this.t = t;


public U whenNull(U whenNull)
return t == null ? whenNull : t;




And usage would be:



Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);


this allows to return a super type; but it looks very weird. We have added another type in the class declaration.



We could resort to:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder)
return holder.t == null ? whenNull : holder.t;




or even make this method static.



For an existing limitation, you could try to do:



Optional.ofNullable(<SomeSubTypeThatIsNull>)
.orElse(<SomeSuperType>)





share|improve this answer















This is handy when you want to return a super type; exactly like you showed in your example.



You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.



This should be an example of what I mean actually. Suppose a very simple class like:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public <U super T> U whenNull(U whenNull)
return t == null ? whenNull : t;




Method whenNull as it is defined would not compile, as U super T is not allowed in java.



Instead you could add another type parameter and invert the types:



static class Holder<U, T extends U> 

private final T t;

public Holder(T t)
this.t = t;


public U whenNull(U whenNull)
return t == null ? whenNull : t;




And usage would be:



Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);


this allows to return a super type; but it looks very weird. We have added another type in the class declaration.



We could resort to:



static class Holder<T> 

private final T t;

public Holder(T t)
this.t = t;


public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder)
return holder.t == null ? whenNull : holder.t;




or even make this method static.



For an existing limitation, you could try to do:



Optional.ofNullable(<SomeSubTypeThatIsNull>)
.orElse(<SomeSuperType>)






share|improve this answer














share|improve this answer



share|improve this answer








edited May 28 at 9:00

























answered May 27 at 11:23









EugeneEugene

75k9104182




75k9104182







  • 7





    But you wouldn't actually need to, because U is assignable to T anyway.

    – RealSkeptic
    May 27 at 11:25











  • I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











  • I think he is right, gonna update my answer accordingly.

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00












  • 7





    But you wouldn't actually need to, because U is assignable to T anyway.

    – RealSkeptic
    May 27 at 11:25











  • I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











  • I think he is right, gonna update my answer accordingly.

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00







7




7





But you wouldn't actually need to, because U is assignable to T anyway.

– RealSkeptic
May 27 at 11:25





But you wouldn't actually need to, because U is assignable to T anyway.

– RealSkeptic
May 27 at 11:25













I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

– Lino
May 27 at 11:29





I agree with @RealSkeptic. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

– Lino
May 27 at 11:29













I think he is right, gonna update my answer accordingly.

– GhostCat
May 27 at 11:31





I think he is right, gonna update my answer accordingly.

– GhostCat
May 27 at 11:31













@RealSkeptic took a while; but edited.

– Eugene
May 27 at 12:38





@RealSkeptic took a while; but edited.

– Eugene
May 27 at 12:38




1




1





@Lino indeed, thank you and edited

– Eugene
May 28 at 9:00





@Lino indeed, thank you and edited

– Eugene
May 28 at 9:00











2














The first method



public static <T, U extends T> T foo(U u) ... 


means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.



With your second example



public static <T> T bar(T t) ... 


bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.






share|improve this answer


















  • 1





    But the object it returns can be assignable or usable in any context that requires its supertype.

    – RealSkeptic
    May 27 at 11:26











  • This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

    – Thomas Kainrad
    May 27 at 11:37











  • @ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











  • I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

    – Thomas Kainrad
    May 27 at 11:44






  • 2





    From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

    – Thomas Kainrad
    May 27 at 12:00















2














The first method



public static <T, U extends T> T foo(U u) ... 


means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.



With your second example



public static <T> T bar(T t) ... 


bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.






share|improve this answer


















  • 1





    But the object it returns can be assignable or usable in any context that requires its supertype.

    – RealSkeptic
    May 27 at 11:26











  • This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

    – Thomas Kainrad
    May 27 at 11:37











  • @ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











  • I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

    – Thomas Kainrad
    May 27 at 11:44






  • 2





    From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

    – Thomas Kainrad
    May 27 at 12:00













2












2








2







The first method



public static <T, U extends T> T foo(U u) ... 


means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.



With your second example



public static <T> T bar(T t) ... 


bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.






share|improve this answer













The first method



public static <T, U extends T> T foo(U u) ... 


means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.



With your second example



public static <T> T bar(T t) ... 


bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 27 at 11:23









Thomas KainradThomas Kainrad

730415




730415







  • 1





    But the object it returns can be assignable or usable in any context that requires its supertype.

    – RealSkeptic
    May 27 at 11:26











  • This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

    – Thomas Kainrad
    May 27 at 11:37











  • @ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











  • I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

    – Thomas Kainrad
    May 27 at 11:44






  • 2





    From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

    – Thomas Kainrad
    May 27 at 12:00












  • 1





    But the object it returns can be assignable or usable in any context that requires its supertype.

    – RealSkeptic
    May 27 at 11:26











  • This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

    – Thomas Kainrad
    May 27 at 11:37











  • @ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











  • I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

    – Thomas Kainrad
    May 27 at 11:44






  • 2





    From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

    – Thomas Kainrad
    May 27 at 12:00







1




1





But the object it returns can be assignable or usable in any context that requires its supertype.

– RealSkeptic
May 27 at 11:26





But the object it returns can be assignable or usable in any context that requires its supertype.

– RealSkeptic
May 27 at 11:26













This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

– Thomas Kainrad
May 27 at 11:37





This is not necessarily true. The method might actually return an object that is not of concrete type U, but of another concrete type X which is also a sub-class of T. There could be scenarios where this is useful.

– Thomas Kainrad
May 27 at 11:37













@ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

– Lino
May 27 at 11:40





@ThomasKainrad though you don't really know what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

– Lino
May 27 at 11:40













I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

– Thomas Kainrad
May 27 at 11:44





I can be sure that the method returns an object of super-type T as this is in its signature. I could then check via instanceof which concrete type it is. This could be X and it would definitely be a subtype of T.

– Thomas Kainrad
May 27 at 11:44




2




2





From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

– Thomas Kainrad
May 27 at 12:00





From my perspective, this argument is not about whether this makes sense or is good design. I only wanted to point out that there are scenarios where the first option provides functionality that is not available with the second option.

– Thomas Kainrad
May 27 at 12:00











2














My first thought was: heck,



Number n = Baz.bar(2);


would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!



Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!



Something like



class B 
class C extends B


now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.



In other words: the U extends T allows you to return instances of B and C. T alone: only C!



But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!



So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.






share|improve this answer




















  • 1





    @RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

    – GhostCat
    May 27 at 11:37






  • 1





    No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





    @RealSkeptic I meant Optional::orElse, my bad, which does return a T

    – Eugene
    May 27 at 11:55






  • 1





    @RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

    – Eugene
    May 27 at 12:15






  • 1





    for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

    – Eugene
    May 27 at 12:16















2














My first thought was: heck,



Number n = Baz.bar(2);


would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!



Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!



Something like



class B 
class C extends B


now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.



In other words: the U extends T allows you to return instances of B and C. T alone: only C!



But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!



So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.






share|improve this answer




















  • 1





    @RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

    – GhostCat
    May 27 at 11:37






  • 1





    No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





    @RealSkeptic I meant Optional::orElse, my bad, which does return a T

    – Eugene
    May 27 at 11:55






  • 1





    @RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

    – Eugene
    May 27 at 12:15






  • 1





    for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

    – Eugene
    May 27 at 12:16













2












2








2







My first thought was: heck,



Number n = Baz.bar(2);


would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!



Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!



Something like



class B 
class C extends B


now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.



In other words: the U extends T allows you to return instances of B and C. T alone: only C!



But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!



So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.






share|improve this answer















My first thought was: heck,



Number n = Baz.bar(2);


would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!



Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!



Something like



class B 
class C extends B


now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.



In other words: the U extends T allows you to return instances of B and C. T alone: only C!



But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!



So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.







share|improve this answer














share|improve this answer



share|improve this answer








edited May 27 at 11:58

























answered May 27 at 11:17









GhostCatGhostCat

102k1797173




102k1797173







  • 1





    @RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

    – GhostCat
    May 27 at 11:37






  • 1





    No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





    @RealSkeptic I meant Optional::orElse, my bad, which does return a T

    – Eugene
    May 27 at 11:55






  • 1





    @RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

    – Eugene
    May 27 at 12:15






  • 1





    for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

    – Eugene
    May 27 at 12:16












  • 1





    @RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

    – GhostCat
    May 27 at 11:37






  • 1





    No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





    @RealSkeptic I meant Optional::orElse, my bad, which does return a T

    – Eugene
    May 27 at 11:55






  • 1





    @RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

    – Eugene
    May 27 at 12:15






  • 1





    for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

    – Eugene
    May 27 at 12:16







1




1





@RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

– GhostCat
May 27 at 11:37





@RealSkeptic But "only C" is NOT the same as "B and C". The above method could always return "just a B". Which is not at all as a C!

– GhostCat
May 27 at 11:37




1




1





No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

– RealSkeptic
May 27 at 11:51





No, @Eugene. It is different than the question, it returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

– RealSkeptic
May 27 at 11:51




1




1





@RealSkeptic I meant Optional::orElse, my bad, which does return a T

– Eugene
May 27 at 11:55





@RealSkeptic I meant Optional::orElse, my bad, which does return a T

– Eugene
May 27 at 11:55




1




1





@RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

– Eugene
May 27 at 12:15





@RealSkeptic @Lino look at this example : static class Holder<T> private final T t; public Holder(T t) this.t = null; // such a method would not compile // public <U super T> whenNull(U defaultValue) // return t == null ? defaultValue : t; // as the comment says - this is not possible. You would need to add another type to be able to do that, via : static class Holder<T, U extends T> ... , but this adds another type parameter... (continue in next comment)

– Eugene
May 27 at 12:15




1




1





for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

– Eugene
May 27 at 12:16





for examples like List<T> or Optional<T> this is never a good idea, just to be able to return a super type. the only solution is to add a static method with the definition of your above to be able to achieve that.

– Eugene
May 27 at 12:16

















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%2f56324835%2fuses-of-t-extends-u%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

Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form