Reputation: 2824
I have recently started reading Core Java. But I am having a hard time grasping the concept of wildcards.
Specifically, I'm confused about the difference between the following:
public class A<T extends {some_class}> {/*...*/}
and
public class A<? extends {some_class}> {/*...*/}
Can anyone help me understand the difference if there is at all?
Upvotes: 1
Views: 160
Reputation: 5173
The difference is that you cannot use the ?
elsewhere while you can use T
. For example:
public class Foo<T extends Number> {
T value; // you can declare fields of type T here
int foo() {
// Since you said T extends Number, you can call methods of Number on value
return value.intValue();
}
}
So why would you use ?
at all? If you don't need the type. It wouldn't make sense to use it in a class definition any way that I can think of. But you could use it in a method like this:
int getListSize(List<?> list) {
return list.size();
}
Any kind of method where you're more interested in the overall class and it has a method that doesn't involve the paramaterized type would work here. Class.getName()
is another example.
Upvotes: 1
Reputation: 121998
? extends some class or T extends some_class
means some_class
itself or any of its children and anything that would work with instanceof some_class.
As per conventions T is meant to be a Type and ?
is unknown type.
Upvotes: 0
Reputation: 171
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
The Type T is a defined type or known type
Hope this helps
Upvotes: 0
Reputation: 425033
They are the same, except with the wildcard you can't refer to the type in the code of your class. Using T
names the type.
Upvotes: 0