开发者

what is the difference between ? and T in class and method signatures?

开发者 https://www.devze.com 2023-04-09 07:36 出处:网络
why does public interface ArrayOfONEITEMInterface <T extends ONEITEMInterface>{ public List<T> getON开发者_Go百科EITEM();

why does

public interface ArrayOfONEITEMInterface <T extends ONEITEMInterface>{
    public List<T> getON开发者_Go百科EITEM();
}

compile, but not

public interface ArrayOfONEITEMInterface <? extends ONEITEMInterface>{
    public List<?> getONEITEM();
}

what is the difference between ? and T in class and method signatures?


? is a wildcard and means any subclass of ONEITEMInterface including itself.

T is a specific implementation of ONEITEMInterface in this case.

Since ? is a wildcard, there is no relation between your ? in the class declaration and the ? in your method declaration hence it won't compile. Just List<?> getONEITEM(); will compile though.


The first scenario means the entire class can handle exactly one type of Bar per instance.

interface Foo<T extends Bar> {
     List<T> get();
}

The second scenario allows each instance to operate on any subtype of Bar

interface Foo {
     List<? extends Bar> get()
}


T is a placeholder for a type that will be provided by an implementing or instantiating class.

? is a placeholder saying "I don't know or care what the generic type is" generally used when the work you'll do on the container object doesn't need to know the type.

The reason you can't use '?' in the class/interface definition is because there's the value is saying defining the name of the placeholder (and the type will be provided elsewhere). Putting a '?' doesn't make sense.

Furthermore, the placeholder doesn't need to be T, it can any standard Java variable. By convention, it is one capital character, but need not be.


? allows you to have a list of Unknown types, where as T requires a definite type.


The clause <T extends ONEITEMInterface> is declaring a type parameter named T. This allows your generic type, ArrayOfONEITEMInterface, to refer to the parameter elsewhere. For example you can declare a method like void add(T t).

Without naming the type parameter, how would you refer to it? If you never refer to the type parameter, why is your type generic in the first place? For example, you don't need a parameterized type to do something like this:

public interface ArrayOfONEITEMInterface {
    List<? extends ONEITEMInterface> getONEITEM();
}

It doesn't make sense to declare an anonymous type parameter, so it is syntactically illegal.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号