Search code examples
javagenericseffective-java

What's the difference between raw types, unbounded wild cards and using Object in generics


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, and Set 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>?


Solution

    • a raw type (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.