silly questions
silly questions

Reputation: 357

Use of wildcard not ask for type cast but use of generics ask in java

Following is method which use ? (wildcard)

public static void doSomething(Set<?> set)
{
    Set<?> copy = new HashSet<Object>(set);
    for (Object o : copy)
    {
        System.out.println(o);
    }
}

Following method with generics

public static <T> void doSomething(Set<T> set)
{
    Set<T> copy = (Set<T>) new HashSet<Object>(set); //Type safety: Unchecked cast from HashSet<Object> to Set<T>
    for (T t : copy)
    {
        System.out.println(t);
    }
}

Both works fine but show warning for second example as shown in comment.

Why there is need of typecast with generics and not with wildcard?

Please help me to understand the concept! thank you ;)

Upvotes: 0

Views: 51

Answers (2)

Prashant Shilimkar
Prashant Shilimkar

Reputation: 8820

Set<?> copy = new HashSet<Object>(set);

Above statement, you are using wildcard ? and that means Set of Any Type.Not required to typecast explicitly. Now here if its other than Object while creating HashSet then it would show compile time error. You can try and play around yourself for better understanding :)

Set<T> copy = (Set<T>) new HashSet<Object>(set);

Above statement means Set of type T. Hence, needs to explicitly typecast. There is no way to tell T is always an Object type. Therefore it shows warning for type safety.

See OracleJavaDocs

Upvotes: 1

eol
eol

Reputation: 24555

Instead of object, directly use the generic type for the Hashset. Also you don't need to cast back to Set since HashSet implements Set. So this should work:

  public static <T> void doSomething(Set<T> set)
    {
        Set<T> copy = new HashSet<T>(set);
        for (T t : copy)
        {
            System.out.println(t);
        }
    }

Upvotes: 1

Related Questions