Uses of T extends U?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}
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
2
@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.5k3 gold badges28 silver badges50 bronze badges
13.5k3 gold badges28 silver badges50 bronze badges
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
2
@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
2
@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
2
2
@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/4.0/"u003ecc by-sa 4.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
45.6k8 gold badges64 silver badges119 bronze badges
45.6k8 gold badges64 silver badges119 bronze badges
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
78.5k9 gold badges112 silver badges194 bronze badges
78.5k9 gold badges112 silver badges194 bronze badges
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
8805 silver badges16 bronze badges
8805 silver badges16 bronze badges
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
111k18 gold badges108 silver badges186 bronze badges
111k18 gold badges108 silver badges186 bronze badges
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
2
@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