天天看点

Set vs. Set<?>

You may know that an unbounded wildcard Set<?> can hold elements of any type, and a raw type Set can also hold elements of any type. What is the difference between them?

There are two facts about Set<?>:

Item 1: Since the question mark ? stands for any type. Set<?> is capable of holding any type of elements.

Item 2: Because we don't know the type of ?, we can't put any element into Set<?>

So a Set<?> can hold any type of element(Item 1), but we can't put any element into it(Item 2). Do the two statements conflict to each other? Of course they are not. This can be clearly illustrated by the following two examples:

Item 1 means the following situation:

Since Set<?> can hold any type of elements, we simply use Object in the loop.

Item 2 means the following situation which is illegal:

Because we don't know the type of <?> exactly, we can not add any thing to it other than null. For the same reason, we can not initialize a set with Set<?>. The following is illegal:

This method declaration is fine:

because raw type has no restrictions. However, this will easily corrupt the invariant of collection.

In brief, wildcard type is safe and the raw type is not. We can not put any element into a Set<?>.

When you want to use a generic type, but you don't know or care what the actual type the parameter is, you can use <?>[1]. It can only be used as parameters for a method.

For example:

Reference:

Bloch, Joshua. Effective java. Addison-Wesley Professional, 2008.

==============================================================================

本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/articles/4237790.html,如需转载请自行联系原作者