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;
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
|
show 5 more comments
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
8
Maybe your simplified example skipped over an aspect where this extraT
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 thisAutoBean<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 anObject
and receive anObject
.
– Lino
May 27 at 11:24
1
That's different. It doesn't returnT
, it returnsSomething<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
extendsObject
butSomething<String>
does not extendsSomething<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 theU
and just replacing it withT
. The example provided by Marco13 is not entirely the same as your example: it is usingList<U>
instead of simplyU
. 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
|
show 5 more comments
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
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
java generics
asked May 27 at 11:03
LinoLino
13.1k32850
13.1k32850
8
Maybe your simplified example skipped over an aspect where this extraT
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 thisAutoBean<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 anObject
and receive anObject
.
– Lino
May 27 at 11:24
1
That's different. It doesn't returnT
, it returnsSomething<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
extendsObject
butSomething<String>
does not extendsSomething<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 theU
and just replacing it withT
. The example provided by Marco13 is not entirely the same as your example: it is usingList<U>
instead of simplyU
. 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
|
show 5 more comments
8
Maybe your simplified example skipped over an aspect where this extraT
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 thisAutoBean<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 anObject
and receive anObject
.
– Lino
May 27 at 11:24
1
That's different. It doesn't returnT
, it returnsSomething<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
extendsObject
butSomething<String>
does not extendsSomething<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 theU
and just replacing it withT
. The example provided by Marco13 is not entirely the same as your example: it is usingList<U>
instead of simplyU
. 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
|
show 5 more comments
4 Answers
4
active
oldest
votes
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)
You're right. In this case it kind of makes sense. Though one could also just writepublic static <T> List<T> withList(List<? extends T> l)
which would work fornumberList = 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 typeU
and not of typeSomething<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 classAutoBean<T>
instead of simpleT
. So it does make sense I guess
– Lino
May 27 at 11:54
5
@Lino Indeed, instead of such aU 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 theU
has to be known for the second parameter.
– Marco13
May 27 at 11:57
add a comment |
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>)
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. HereU
would still be assignable toT
soT
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
add a comment |
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.
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 whatT
really is. As the whole context is generic. You can't be sure thatX
really is a subtype ofT
– Lino
May 27 at 11:40
I can be sure that the method returns an object of super-typeT
as this is in its signature. I could then check viainstanceof
which concrete type it is. This could beX
and it would definitely be a subtype ofT
.
– 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
|
show 1 more comment
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
.
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 returnsSomething<T>
rather thanT
, which means it's not polymorphic withSomething<U>
, whereasT
is polymorphic withU
. Take a look at the comments to the OP.
– RealSkeptic
May 27 at 11:51
1
@RealSkeptic I meantOptional::orElse
, my bad, which does return aT
– 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 likeList<T>
orOptional<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
|
show 11 more comments
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)
You're right. In this case it kind of makes sense. Though one could also just writepublic static <T> List<T> withList(List<? extends T> l)
which would work fornumberList = 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 typeU
and not of typeSomething<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 classAutoBean<T>
instead of simpleT
. So it does make sense I guess
– Lino
May 27 at 11:54
5
@Lino Indeed, instead of such aU 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 theU
has to be known for the second parameter.
– Marco13
May 27 at 11:57
add a comment |
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)
You're right. In this case it kind of makes sense. Though one could also just writepublic static <T> List<T> withList(List<? extends T> l)
which would work fornumberList = 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 typeU
and not of typeSomething<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 classAutoBean<T>
instead of simpleT
. So it does make sense I guess
– Lino
May 27 at 11:54
5
@Lino Indeed, instead of such aU 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 theU
has to be known for the second parameter.
– Marco13
May 27 at 11:57
add a comment |
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)
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)
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 writepublic static <T> List<T> withList(List<? extends T> l)
which would work fornumberList = 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 typeU
and not of typeSomething<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 classAutoBean<T>
instead of simpleT
. So it does make sense I guess
– Lino
May 27 at 11:54
5
@Lino Indeed, instead of such aU 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 theU
has to be known for the second parameter.
– Marco13
May 27 at 11:57
add a comment |
You're right. In this case it kind of makes sense. Though one could also just writepublic static <T> List<T> withList(List<? extends T> l)
which would work fornumberList = 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 typeU
and not of typeSomething<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 classAutoBean<T>
instead of simpleT
. So it does make sense I guess
– Lino
May 27 at 11:54
5
@Lino Indeed, instead of such aU 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 theU
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
add a comment |
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>)
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. HereU
would still be assignable toT
soT
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
add a comment |
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>)
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. HereU
would still be assignable toT
soT
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
add a comment |
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>)
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>)
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. HereU
would still be assignable toT
soT
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
add a comment |
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. HereU
would still be assignable toT
soT
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
add a comment |
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.
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 whatT
really is. As the whole context is generic. You can't be sure thatX
really is a subtype ofT
– Lino
May 27 at 11:40
I can be sure that the method returns an object of super-typeT
as this is in its signature. I could then check viainstanceof
which concrete type it is. This could beX
and it would definitely be a subtype ofT
.
– 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
|
show 1 more comment
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.
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 whatT
really is. As the whole context is generic. You can't be sure thatX
really is a subtype ofT
– Lino
May 27 at 11:40
I can be sure that the method returns an object of super-typeT
as this is in its signature. I could then check viainstanceof
which concrete type it is. This could beX
and it would definitely be a subtype ofT
.
– 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
|
show 1 more comment
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.
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.
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 whatT
really is. As the whole context is generic. You can't be sure thatX
really is a subtype ofT
– Lino
May 27 at 11:40
I can be sure that the method returns an object of super-typeT
as this is in its signature. I could then check viainstanceof
which concrete type it is. This could beX
and it would definitely be a subtype ofT
.
– 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
|
show 1 more comment
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 whatT
really is. As the whole context is generic. You can't be sure thatX
really is a subtype ofT
– Lino
May 27 at 11:40
I can be sure that the method returns an object of super-typeT
as this is in its signature. I could then check viainstanceof
which concrete type it is. This could beX
and it would definitely be a subtype ofT
.
– 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
|
show 1 more comment
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
.
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 returnsSomething<T>
rather thanT
, which means it's not polymorphic withSomething<U>
, whereasT
is polymorphic withU
. Take a look at the comments to the OP.
– RealSkeptic
May 27 at 11:51
1
@RealSkeptic I meantOptional::orElse
, my bad, which does return aT
– 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 likeList<T>
orOptional<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
|
show 11 more comments
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
.
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 returnsSomething<T>
rather thanT
, which means it's not polymorphic withSomething<U>
, whereasT
is polymorphic withU
. Take a look at the comments to the OP.
– RealSkeptic
May 27 at 11:51
1
@RealSkeptic I meantOptional::orElse
, my bad, which does return aT
– 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 likeList<T>
orOptional<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
|
show 11 more comments
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
.
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
.
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 returnsSomething<T>
rather thanT
, which means it's not polymorphic withSomething<U>
, whereasT
is polymorphic withU
. Take a look at the comments to the OP.
– RealSkeptic
May 27 at 11:51
1
@RealSkeptic I meantOptional::orElse
, my bad, which does return aT
– 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 likeList<T>
orOptional<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
|
show 11 more comments
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 returnsSomething<T>
rather thanT
, which means it's not polymorphic withSomething<U>
, whereasT
is polymorphic withU
. Take a look at the comments to the OP.
– RealSkeptic
May 27 at 11:51
1
@RealSkeptic I meantOptional::orElse
, my bad, which does return aT
– 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 likeList<T>
orOptional<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
|
show 11 more comments
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 anObject
and receive anObject
.– Lino
May 27 at 11:24
1
That's different. It doesn't return
T
, it returnsSomething<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
extendsObject
butSomething<String>
does not extendsSomething<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 theU
and just replacing it withT
. The example provided by Marco13 is not entirely the same as your example: it is usingList<U>
instead of simplyU
. 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