Uses of T extends U?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}








17















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



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


A sample use could be like this:



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


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



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


If I call it like this:



Number n = Baz.bar(2);


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



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










share|improve this question




















  • 8





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

    – Thilo
    May 27 at 11:16











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

    – Lino
    May 27 at 11:24






  • 1





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

    – RealSkeptic
    May 27 at 11:27











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

    – Lino
    May 27 at 11:34








  • 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




















17















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



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


A sample use could be like this:



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


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



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


If I call it like this:



Number n = Baz.bar(2);


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



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










share|improve this question




















  • 8





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

    – Thilo
    May 27 at 11:16











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

    – Lino
    May 27 at 11:24






  • 1





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

    – RealSkeptic
    May 27 at 11:27











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

    – Lino
    May 27 at 11:34








  • 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
















17












17








17


3






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



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


A sample use could be like this:



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


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



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


If I call it like this:



Number n = Baz.bar(2);


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



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










share|improve this question














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



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


A sample use could be like this:



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


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



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


If I call it like this:



Number n = Baz.bar(2);


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



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







java generics






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 27 at 11:03









LinoLino

13.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 extra T makes sense. Can you link/include the real signature?

    – Thilo
    May 27 at 11:16











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

    – Lino
    May 27 at 11:24






  • 1





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

    – RealSkeptic
    May 27 at 11:27











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

    – Lino
    May 27 at 11:34








  • 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
















  • 8





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

    – Thilo
    May 27 at 11:16











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

    – Lino
    May 27 at 11:24






  • 1





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

    – RealSkeptic
    May 27 at 11:27











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

    – Lino
    May 27 at 11:34








  • 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










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














4 Answers
4






active

oldest

votes


















9
















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



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



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





A small update:



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



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





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



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

public class SupertypeMethod {
public static void main(String args) {

Integer integer = null;
Number number = null;

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

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

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

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

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

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

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

}


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






share|improve this answer




























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

    – Lino
    May 27 at 11:48











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

    – MC Emperor
    May 27 at 11:52











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

    – Lino
    May 27 at 11:54








  • 5





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

    – Marco13
    May 27 at 11:57



















4
















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



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



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



static class Holder<T> {

private final T t;

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

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


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



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



static class Holder<U, T extends U> {

private final T t;

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

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


And usage would be:



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


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



We could resort to:



static class Holder<T> {

private final T t;

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

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


or even make this method static.



For an existing limitation, you could try to do:



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





share|improve this answer























  • 7





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

    – RealSkeptic
    May 27 at 11:25











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

    – Lino
    May 27 at 11:29











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

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00



















2
















The first method



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


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



With your second example



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


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






share|improve this answer





















  • 1





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

    – RealSkeptic
    May 27 at 11:26











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

    – Thomas Kainrad
    May 27 at 11:37











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

    – Lino
    May 27 at 11:40











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

    – Thomas Kainrad
    May 27 at 11:44






  • 2





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

    – Thomas Kainrad
    May 27 at 12:00



















2
















My first thought was: heck,



Number n = Baz.bar(2);


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



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



Something like



class B { } 
class C extends B { }


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



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



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



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






share|improve this answer























  • 1





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

    – GhostCat
    May 27 at 11:37






  • 1





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

    – RealSkeptic
    May 27 at 11:51






  • 1





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

    – Eugene
    May 27 at 11:55






  • 1





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

    – Eugene
    May 27 at 12:15






  • 1





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

    – Eugene
    May 27 at 12:16













Your Answer






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

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

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

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/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
});


}
});















draft saved

draft discarded
















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56324835%2fuses-of-t-extends-u%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























4 Answers
4






active

oldest

votes








4 Answers
4






active

oldest

votes









active

oldest

votes






active

oldest

votes









9
















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



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



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





A small update:



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



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





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



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

public class SupertypeMethod {
public static void main(String args) {

Integer integer = null;
Number number = null;

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

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

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

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

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

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

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

}


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






share|improve this answer




























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

    – Lino
    May 27 at 11:48











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

    – MC Emperor
    May 27 at 11:52











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

    – Lino
    May 27 at 11:54








  • 5





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

    – Marco13
    May 27 at 11:57
















9
















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



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



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





A small update:



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



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





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



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

public class SupertypeMethod {
public static void main(String args) {

Integer integer = null;
Number number = null;

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

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

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

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

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

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

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

}


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






share|improve this answer




























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

    – Lino
    May 27 at 11:48











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

    – MC Emperor
    May 27 at 11:52











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

    – Lino
    May 27 at 11:54








  • 5





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

    – Marco13
    May 27 at 11:57














9














9










9









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



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



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





A small update:



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



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





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



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

public class SupertypeMethod {
public static void main(String args) {

Integer integer = null;
Number number = null;

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

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

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

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

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

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

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

}


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






share|improve this answer















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



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



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





A small update:



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



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





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



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

public class SupertypeMethod {
public static void main(String args) {

Integer integer = null;
Number number = null;

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

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

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

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

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

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

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

}


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







share|improve this answer














share|improve this answer



share|improve this answer








edited May 27 at 12:07

























answered May 27 at 11:40









Marco13Marco13

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 write public static <T> List<T> withList(List<? extends T> l) which would work for numberList = withList(integerList). Maybe this is just some redundancy in the java language

    – Lino
    May 27 at 11:48











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

    – MC Emperor
    May 27 at 11:52











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

    – Lino
    May 27 at 11:54








  • 5





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

    – Marco13
    May 27 at 11:57



















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

    – Lino
    May 27 at 11:48











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

    – MC Emperor
    May 27 at 11:52











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

    – Lino
    May 27 at 11:54








  • 5





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

    – Marco13
    May 27 at 11:57

















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

– Lino
May 27 at 11:48





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

– Lino
May 27 at 11:48













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

– MC Emperor
May 27 at 11:52





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

– MC Emperor
May 27 at 11:52













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

– Lino
May 27 at 11:54







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

– Lino
May 27 at 11:54






5




5





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

– Marco13
May 27 at 11:57





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

– Marco13
May 27 at 11:57













4
















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



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



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



static class Holder<T> {

private final T t;

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

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


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



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



static class Holder<U, T extends U> {

private final T t;

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

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


And usage would be:



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


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



We could resort to:



static class Holder<T> {

private final T t;

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

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


or even make this method static.



For an existing limitation, you could try to do:



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





share|improve this answer























  • 7





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

    – RealSkeptic
    May 27 at 11:25











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

    – Lino
    May 27 at 11:29











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

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00
















4
















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



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



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



static class Holder<T> {

private final T t;

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

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


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



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



static class Holder<U, T extends U> {

private final T t;

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

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


And usage would be:



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


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



We could resort to:



static class Holder<T> {

private final T t;

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

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


or even make this method static.



For an existing limitation, you could try to do:



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





share|improve this answer























  • 7





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

    – RealSkeptic
    May 27 at 11:25











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

    – Lino
    May 27 at 11:29











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

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00














4














4










4









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



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



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



static class Holder<T> {

private final T t;

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

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


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



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



static class Holder<U, T extends U> {

private final T t;

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

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


And usage would be:



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


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



We could resort to:



static class Holder<T> {

private final T t;

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

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


or even make this method static.



For an existing limitation, you could try to do:



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





share|improve this answer















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



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



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



static class Holder<T> {

private final T t;

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

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


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



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



static class Holder<U, T extends U> {

private final T t;

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

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


And usage would be:



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


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



We could resort to:



static class Holder<T> {

private final T t;

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

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


or even make this method static.



For an existing limitation, you could try to do:



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






share|improve this answer














share|improve this answer



share|improve this answer








edited May 28 at 9:00

























answered May 27 at 11:23









EugeneEugene

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. Here U would still be assignable to T so T should be enough as you could pass any sub-type to said method

    – Lino
    May 27 at 11:29











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

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00














  • 7





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

    – RealSkeptic
    May 27 at 11:25











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

    – Lino
    May 27 at 11:29











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

    – GhostCat
    May 27 at 11:31











  • @RealSkeptic took a while; but edited.

    – Eugene
    May 27 at 12:38






  • 1





    @Lino indeed, thank you and edited

    – Eugene
    May 28 at 9:00








7




7





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

– RealSkeptic
May 27 at 11:25





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

– RealSkeptic
May 27 at 11:25













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

– Lino
May 27 at 11:29





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

– Lino
May 27 at 11:29













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

– GhostCat
May 27 at 11:31





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

– GhostCat
May 27 at 11:31













@RealSkeptic took a while; but edited.

– Eugene
May 27 at 12:38





@RealSkeptic took a while; but edited.

– Eugene
May 27 at 12:38




1




1





@Lino indeed, thank you and edited

– Eugene
May 28 at 9:00





@Lino indeed, thank you and edited

– Eugene
May 28 at 9:00











2
















The first method



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


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



With your second example



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


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






share|improve this answer





















  • 1





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

    – RealSkeptic
    May 27 at 11:26











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

    – Thomas Kainrad
    May 27 at 11:37











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

    – Lino
    May 27 at 11:40











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

    – Thomas Kainrad
    May 27 at 11:44






  • 2





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

    – Thomas Kainrad
    May 27 at 12:00
















2
















The first method



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


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



With your second example



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


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






share|improve this answer





















  • 1





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

    – RealSkeptic
    May 27 at 11:26











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

    – Thomas Kainrad
    May 27 at 11:37











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

    – Lino
    May 27 at 11:40











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

    – Thomas Kainrad
    May 27 at 11:44






  • 2





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

    – Thomas Kainrad
    May 27 at 12:00














2














2










2









The first method



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


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



With your second example



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


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






share|improve this answer













The first method



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


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



With your second example



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


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







share|improve this answer












share|improve this answer



share|improve this answer










answered May 27 at 11:23









Thomas KainradThomas Kainrad

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 what T really is. As the whole context is generic. You can't be sure that X really is a subtype of T

    – Lino
    May 27 at 11:40











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

    – Thomas Kainrad
    May 27 at 11:44






  • 2





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

    – Thomas Kainrad
    May 27 at 12:00














  • 1





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

    – RealSkeptic
    May 27 at 11:26











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

    – Thomas Kainrad
    May 27 at 11:37











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

    – Lino
    May 27 at 11:40











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

    – Thomas Kainrad
    May 27 at 11:44






  • 2





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

    – Thomas Kainrad
    May 27 at 12:00








1




1





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

– RealSkeptic
May 27 at 11:26





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

– RealSkeptic
May 27 at 11:26













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

– Thomas Kainrad
May 27 at 11:37





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

– Thomas Kainrad
May 27 at 11:37













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

– Lino
May 27 at 11:40





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

– Lino
May 27 at 11:40













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

– Thomas Kainrad
May 27 at 11:44





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

– Thomas Kainrad
May 27 at 11:44




2




2





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

– Thomas Kainrad
May 27 at 12:00





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

– Thomas Kainrad
May 27 at 12:00











2
















My first thought was: heck,



Number n = Baz.bar(2);


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



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



Something like



class B { } 
class C extends B { }


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



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



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



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






share|improve this answer























  • 1





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

    – GhostCat
    May 27 at 11:37






  • 1





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

    – RealSkeptic
    May 27 at 11:51






  • 1





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

    – Eugene
    May 27 at 11:55






  • 1





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

    – Eugene
    May 27 at 12:15






  • 1





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

    – Eugene
    May 27 at 12:16
















2
















My first thought was: heck,



Number n = Baz.bar(2);


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



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



Something like



class B { } 
class C extends B { }


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



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



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



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






share|improve this answer























  • 1





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

    – GhostCat
    May 27 at 11:37






  • 1





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

    – RealSkeptic
    May 27 at 11:51






  • 1





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

    – Eugene
    May 27 at 11:55






  • 1





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

    – Eugene
    May 27 at 12:15






  • 1





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

    – Eugene
    May 27 at 12:16














2














2










2









My first thought was: heck,



Number n = Baz.bar(2);


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



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



Something like



class B { } 
class C extends B { }


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



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



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



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






share|improve this answer















My first thought was: heck,



Number n = Baz.bar(2);


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



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



Something like



class B { } 
class C extends B { }


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



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



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



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







share|improve this answer














share|improve this answer



share|improve this answer








edited May 27 at 11:58

























answered May 27 at 11:17









GhostCatGhostCat

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 returns Something<T> rather than T, which means it's not polymorphic with Something<U>, whereas T is polymorphic with U. Take a look at the comments to the OP.

    – RealSkeptic
    May 27 at 11:51






  • 1





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

    – Eugene
    May 27 at 11:55






  • 1





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

    – Eugene
    May 27 at 12:15






  • 1





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

    – Eugene
    May 27 at 12:16














  • 1





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

    – GhostCat
    May 27 at 11:37






  • 1





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

    – RealSkeptic
    May 27 at 11:51






  • 1





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

    – Eugene
    May 27 at 11:55






  • 1





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

    – Eugene
    May 27 at 12:15






  • 1





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

    – Eugene
    May 27 at 12:16








1




1





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

– GhostCat
May 27 at 11:37





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

– GhostCat
May 27 at 11:37




1




1





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

– RealSkeptic
May 27 at 11:51





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

– RealSkeptic
May 27 at 11:51




1




1





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

– Eugene
May 27 at 11:55





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

– Eugene
May 27 at 11:55




1




1





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

– Eugene
May 27 at 12:15





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

– Eugene
May 27 at 12:15




1




1





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

– Eugene
May 27 at 12:16





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

– Eugene
May 27 at 12:16



















draft saved

draft discarded



















































Thanks for contributing an answer to Stack Overflow!


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

But avoid



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

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


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




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56324835%2fuses-of-t-extends-u%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum

He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

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