d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > What's The Difference
Add Reply New Topic New Poll
Member
Posts: 31,292
Joined: Mar 25 2009
Gold: 0.00
May 3 2022 02:40pm
<T extends Liquid>

<? extends Liquid>

using T vs wildcard?

with generics




What's the difference between them, and what situation would you use either of them?

This post was edited by ferf on May 3 2022 02:43pm
Member
Posts: 17,374
Joined: Jul 6 2007
Gold: 12,143.67
May 3 2022 02:58pm
iirc they're functionally similar in terms of declarations, so generally it's a code style thing

wildcards however can't have trait bounds iirc
Member
Posts: 12,703
Joined: May 17 2013
Gold: 12,935.00
May 4 2022 02:12am
your first issue was considering Generics in java, which aren't properly enforced at runtime :-)

wildcards mean you go outside of type safe methods - you can't enforce that the return type is related to the input type (which is usually the point of using generics)

if you are familiar with dynamically typed languages, wildcards in Java are used to support operations on arbitrary types that you can do to return another type, e.g. summing values (floats/longs/ints/etc..) in lists and returning just a float, no matter what the input type is.

in the case of <? extends Liquid>, it means you require the input type to be a subclass of Liquid, but you can't enforce the return type of a function with this parameter signature
Member
Posts: 16,658
Joined: Nov 10 2010
Gold: 13.50
May 5 2022 06:16am
Just try and learn as you use them :D
Member
Posts: 18
Joined: May 9 2022
Gold: 60.00
May 12 2022 02:09am
T is type safe. Take example:
Quote
public static <T extends Number> void copy(List<T> dest, List<T> src)

In that case you will have parameters and method return of a same type(at least of same Number abstraction)

In case of using "?" wildcard you are no longer type safe. Example:
Quote
public static void foo(List<? extends Number> dest, List<? extends Number> src)

You can pass dest type Integer, src type Float.
Use wildcard when you need no boundries on parameter types, no relation on them.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll