18

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.

Lino
  • 19,604
  • 6
  • 47
  • 65
  • 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 '19 at 11:16
  • @Thilo I don't have a real code sample. I encountered it when seeing [this question](https://stackoverflow.com/q/15491058/5515060). The usage there seems to be a Bean resolving mechanism where you could define a delegate. E.g. like this `AutoBean autoBean = Foo.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 '19 at 11:24
  • 1
    That's different. It doesn't return `T`, it returns `Something`. – RealSkeptic May 27 '19 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` does **not** extends `Something` – Lino May 27 '19 at 11:34
  • Exactly. Which means that if you update the question with this information... it will be closed as a duplicate. – RealSkeptic May 27 '19 at 11:37
  • It *could* be that it helps the compiler to solve inference problems. – MC Emperor May 27 '19 at 11:44
  • @MCEmperor this could still be worked around using "type hints", e.g. `Object o = Baz..foo("hello")`, but I agree. Maybe it's just another way of doing things I guess – Lino May 27 '19 at 11:51
  • 2
    @Lino Yeah, but I'm still not convinced. I don't think your *specific* of ` 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` instead of simply `U`**. I agree that in the context of *parameterized type*s (`Something`) 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 '19 at 11:57
  • @RealSkeptic I agree. I've accepted [Marco13's answer](https://stackoverflow.com/a/56325352/5515060) though as they point it out that I made an interpretation mistake (and it's just a nice answer too). But feel free to drop that duplicate here. Happy to close it anyway as my confusion has been lifted – Lino May 27 '19 at 11:58
  • @MCEmperor I can only agree with you. There is probably no use case for just simple arguments with generic types. Parameterized classes are a different but valid use case as illustrated by Marco13 – Lino May 27 '19 at 12:02

4 Answers4

12

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)

Marco13
  • 53,703
  • 9
  • 80
  • 159
  • You're right. In this case it kind of makes sense. Though one could also just write `public static List 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 '19 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`, I cannot imagine a case where it actually makes a difference. – MC Emperor May 27 '19 at 11:52
  • @MCEmperor actually I kind of missinterpreted the [code where I've seen it](https://stackoverflow.com/q/15491058/5515060). In that question they return a parameterized class `AutoBean` instead of simple `T`. So it does make sense I guess – Lino May 27 '19 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 copyAndAdd(List us, U anotherU)` where the `U` has to be known for the second parameter. – Marco13 May 27 '19 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>)
Eugene
  • 117,005
  • 15
  • 201
  • 306
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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • of course there is; by introducing `U` - you can now return a `super-type`, with plain `T` - you can't. – Eugene May 27 '19 at 11:24
  • @Eugene Yep, figured that by now, and hopefully made it more clear now. – GhostCat May 27 '19 at 11:33
  • But again, if it returns "only C", you can still assign the result to `B`, pass it as a `B` parameter, etc. – RealSkeptic May 27 '19 at 11:36
  • 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 '19 at 11:37
  • I think that is the answer. But I am still skeptical, imagine you're the method. And you get a parameter of type `U` and have to return `T`. You still don't know the exact types do you? You can't write `return new T()` because you simply don't know what `T` is. Maybe it works if one introduces another layer of abstraction. E.g. having another class that returns only instances of `T`. Maybe I am thinking too far though – Lino May 27 '19 at 11:38
  • Yes, I don't see any way the method could return something that was the supertype but not the subtype, except if it did something in reflection, and then it would not be applicable to all types. – RealSkeptic May 27 '19 at 11:41
  • @Lino you are almost there IMO... take `Optional::or` for example. try to create a `Optional.ofNullable().or()`... can you? – Eugene May 27 '19 at 11:42
  • @Eugene That's exactly because `ofNullable` does not return a supertype of its parameter, but an `Optional`. – RealSkeptic May 27 '19 at 11:48
  • @RealSkeptic exactly. but a definition of `T super U` is not allowed; so it can't be done otherwise, unless you declare a static method with the definition as in the question. – Eugene May 27 '19 at 11:50
  • 1
    No, @Eugene. It is *different* than the question, it returns `Something` rather than `T`, which means it's not polymorphic with `Something`, whereas `T` *is* polymorphic with `U`. Take a look at the comments to the OP. – RealSkeptic May 27 '19 at 11:51
  • 1
    @RealSkeptic I meant `Optional::orElse`, my bad, which does return a `T` – Eugene May 27 '19 at 11:55
  • @RealSkeptic I didn't say that it is of much practical value in the real world ;-) – GhostCat May 27 '19 at 11:56
  • @Lino I just updated my answer again. I agree about that "practical" point of view. – GhostCat May 27 '19 at 12:04
  • @GhostCat Yep, as seen in other answers. The usability of arguments with a generic type is quite strict and doesn't make sense in this usage context. Parameterized classes, like `List` and `List`, are a whole different chapter though and there are some cases where this construct makes sense. – Lino May 27 '19 at 12:07
  • 1
    @RealSkeptic @Lino look at this example : `static class Holder { private final T t; public Holder(T t) { this.t = null; } // such a method would not compile // public 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 {... }`, but this adds another type parameter... (continue in next comment) – Eugene May 27 '19 at 12:15
  • 1
    for examples like `List` or `Optional` 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 '19 at 12:16
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.

Thomas Kainrad
  • 2,542
  • 21
  • 26
  • 1
    But the object it returns can be assignable or usable in any context that requires its supertype. – RealSkeptic May 27 '19 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 '19 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 '19 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 '19 at 11:44
  • @ThomasKainrad using `instanceof` defeats the whole purpose of generics in the first place imo. But yes I agree, that could be a usage – Lino May 27 '19 at 11:49
  • 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 '19 at 12:00