I've got a class foo, a class that derives from food called bar, and I've got a method in foo that takes another foo
boolean baz(foo c)
{
return (condition)?true:false;
}
I want to write an overload for baz that takes a Vector and calls baz on all of them -- something like
boolean baz(Vector<foo> v)
{
for(int i=0;i<v.size();++i)
{
if baz(v.get(i))
return true;
}
return false;
}
and I want to use call this method on a Vector of bar. I tried writing this in the way I just outlined, and I get compiler errors when I try to call this method on a vector of bar.
What开发者_如何转开发 am I missing?
This is expected, because generics are invariant.
List<Derived>
is not List<Base>
. Imagine if you call that method, but inside it you call list.add(anotherDerived)
.
You can "fix" this by using List<? extends Base>
. Thus you won't be able to add elements, and hence won't be able to violate the generics contract.
(I'm using List
instead of Vector
, because Vector
is replaced (in most cases) by ArrayList
)
Just declare the method like this:
boolean baz(Vector<? extends foo> v)
Two additional points:
- Java has an extremely strong convention for class names beginning with an uppercase letter. Anyone reading your code will be irritated by lowercase class names.
Vector
is an obsolete class that should not be used anymore unless you're dealing with an API that does and which you don't control (like some parts of AWT). UseArrayList
instead.
instead of :
boolean baz(Vector<foo> v)
try
boolean baz(Vector<? extends foo> v)
精彩评论