Reputation: 21124
Say I've got two interfaces:
public interface IObjectOne<T>
{
List<T> digest(final List<T> myList);
}
public interface IObjectTwo<T>
{
List<T> create();
}
And an object which manages concrete implementations of these two interfaces, which must work over the same type.
public class Entity<T>
{
private IObjectOne<T> objectOne;
private IObjectTwo<T> objectTwo;
... setters
public IObjectOne<T> getObjectOne() {
return objectOne;
}
public IObjectTwo<T> getObjectTwo() {
return objectTwo;
}
}
These Entity
s are stored in a Map
, and I retrive one of them by a key:
final Entity<?> entity = entities.get(key);
Why cannot I do that?
entity.getObjectOne().digest(entity.getObjectTwo().create());
Upvotes: 0
Views: 182
Reputation: 140427
Here:
final Entity<?> entity = entities.get(key);
you are saying: you absolutely do not care about the exact type of an entity. Reminder: wildcard means "I don't know" about the exact type.
And one consequence of using the wildcard for generics, as described here:
If you want to enforce some relationship on the different types of method arguments, you can't do that with wildcards, you have to use type parameters.
In other words: by using the wildcard like this, the compiler is unable to correlate the generic types.
Upvotes: 2
Reputation: 4699
How are you creating the Map<String, Entity<YOUR_TYPE>>
You should parameterize your Entity<>
since it is generic.
Map<String, Entity<YOUR_TYPE>> entities = new HashMap<>();
final Entity<YourType> entity = entities.get(key);
Upvotes: 0
Reputation: 140319
To do this, you need to do your operation in a method with a type variable:
<T> void doSomething(Entity<T> entity) {
entity.getObjectOne().digest(entity.getObjectTwo().create());
}
You can invoke this even for an Entity<?>
, because that wildcard has some type, you just don't know it.
final Entity<?> entity = entities.get(key);
doSomething(entity);
Upvotes: 2