Inheritance with generics + collection + method = question
I have some problem with generics and collection. Java support generics only at compilation level. So we can't use case B.
{
foo(开发者_StackOverflownew 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.
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.
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);}
精彩评论