Reputation: 15792
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.
Upvotes: 1
Views: 347
Reputation: 11017
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);}
Upvotes: 1
Reputation: 1500555
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.
Upvotes: 4