I am reading the chapter on Generics in Effective Java.
Help me understand difference between Set
, Set<?>
and Set<Object>
?
The following paragraph is taken from the book.
As a quick review,
Set<Object>
is a parameterized type representing a set that can contain objects of any type,Set<?>
is a wildcard type representing a set that can contain only objects of some unknown type, andSet
is a raw type, which opts out of the generic type system.
What is meant by "some unknown type"? Are all unknown types of type Object
? In that case what is the specific difference between Set<?>
and Set<Object>
?
both bounded and unbounded wildcards provide a lot of flexibility on API design especially because Generics is not covariant and List<String> can not be used in place of List<Object>. Bounded wildcards allow you to write methods that can operate on Collection of Type as well as Collection of Type subclasses.
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.
The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach: If you are writing a method that can be implemented using functionality provided in the Object class.
Guidelines for Wildcards. Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard. Lower bound wildcard − If a variable is of out category, use super keyword with wildcard. Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard.
Set
) treats the type as if it had no generic type information at all. Note the subtle effect that not only will the type argument T
be ignored, but also all other type arguments that methods of that type might have. You can add any value to it and it will always return Object
.Set<Object>
is a Set
that accepts all Object
objects (i.e. all objects) and will return objects of type Object
.Set<?>
is a Set
that accepts all objects of some specific, but unknown type and will return objects of that type. Since nothing is known about this type, you can't add anything to that set (except for null
) and the only thing that you know about the values it returns is that they are some sub-type of Object
.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