1

I have some problem with generics and collection. Java support generics only at compilation level. So we can't use case B.

{
    foo(new HashSet<I>());  //case A
    foo(new HashSet<C>());  //case B: wrong
}
void foo(Set<I> set){}
class C implements I{}
interface I {}

So how we can use function foo with Set< C > parameter?

Thanks.

2 Answers 2

4

By changing the signature of Foo:

void foo(Set<? extends I> set){}

You won't be able to add values to the set within foo, but you'll be able to iterate over them or check for containment.

Sign up to request clarification or add additional context in comments.

Comments

1

Jon Skeet is right. If you did need to add something, however, you could write a generic function

public <T extends I> void foo2(Set<T> set, T added){set.add(added);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.