I have read that <?>
is exactly the same as <? extends Object>
. Then what is the difference between:
Set<?>
Set<Object>
Set
I've tried adding String.class
and MyClass.class
into all these sets but in the second case it doesn't compile.
Another example I don't get is:
Set<Class>
Set<Class<?>>
To me it seems they are identical but if I have a method which returns Set<Class<?>>
, I can't assign it's return value to variable of type Set<Class>
.
I am sorry if this is duplicate, but I have read all the other posts and there are very few examples and I still can't understand it.
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.
In the Java programming language, the wildcard ? is a special kind of type argument that controls the type safety of the use of generic (parameterized) types. It can be used in variable declarations and instantiations as well as in method definitions, but not in the definition of a generic type.
We can use the Java Wildcard as a local variable, parameter, field or as a return type. But, when the generic class is instantiated or when a generic method is called, we can't use wildcards. The wildcard is useful to remove the incompatibility between different instantiations of a generic type.
Bounded and unbounded wildcards in Generics are two types of wildcards available on Java. Any Type can be bounded either upper or lower of the class hierarchy in Generics by using bounded wildcards.
with Set<?>
, i can use any type i want like : Set<?> s =new HashSet<Intger>()
or Set<?> s =new HashSet<String>()
.Since, i can make ?
refer to anything i'm not allowed to put anything other than null
in the collection and i will get Object
out of the collection.
Set<Object>
says i can only assign type Object
for ex : Set<Object> s =new HashSet<Object>()
but not Set<Object> s =new HashSet<String>()
.In this case i can add any type because Object
is the super base type but i will get Object
out of the collection.
Set
is the basic raw type , you can add anything and get an Object
type out of it.
Set<Class>
is different than Set<Class<?>>
.The first one says "I am a Set of non specific Class
types " while the second one says "I am a Set of some specific Class
types but don't know which".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With