I'm trying to create a kind of service locator class, where there is a
Map<Integer, ? extends ISomething>
but I can't later do
myMap.put(0x00, new SomethingImplementor())
As I get a Error:(18, 33) java: incompatible types: org.sample.SomethingImplementor cannot be converted to capture#1 of ? extends ISomething
My class structure is as follows:
public interface ISomething {
public void doSomething();
}
public class SomethingImplementor implements ISomething {
@Override public void doSomething() {...}
}
Why can't I create this map and put values into it?
You don't need the wildcard at all.
You can directly use
Map<Integer, ISomething>
and you can implement every subclass of ISomething
.
Anyway, to work with wildcards in this case you should use super
. With extends
you don't know what type it will be so you can't add anything to the map.
List is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.
There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:
You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.
Wildcards: http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments