Last Updated:

What is the difference between Set and Set with a question mark |  Example 

Features of using Set<?>

It is known that a set of Set<?> can contain any type of element inside, but the idea is that we cannot add elements to it. At first glance, these two facts contradict each other, but let's look at a simple example:

Let's analyze the code above:

Knowing that Set<> can accept any type of element, we simply use an object of type Object to bypass all the elements of the set.

Now consider this situation:

In the changeSet() method, the set is defined as <?>, which means that we do not know exactly what type of data it contains, so we cannot add anything to this set. The only exception is null.

If you rewrite the above method as:

The Set set has no such limitations. However, using this approach can lead to possible errors in the future.

Where to use Set<?> and how is it useful?

Let's look at the case when Set<?> is really useful:

As you can see, Set<> is useful in utility methods that somehow process the elements of a set without changing the collection itself.