Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark in Java generics

I have read that <?> is exactly the same as <? extends Object>. Then what is the difference between:

  1. Set<?>
  2. Set<Object>
  3. 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:

  1. Set<Class>
  2. 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.

like image 353
Samuel Avatar asked Nov 30 '15 11:11

Samuel


People also ask

Why do we use question mark in Java?

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.

What is wildcard generics in Java?

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.

Why do we need wildcard in generics in Java?

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.

What is bounded and unbounded wildcards in generics Java?

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.


1 Answers

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".

like image 87
Ramanlfc Avatar answered Sep 27 '22 20:09

Ramanlfc