I can't figure out a solution to my problem. In both of these cases I get a compile error. Any help to make it work?
Case 1:
public class Entity<T extends EntityHandler<Entity>> {
protected T handler;
public void remove() {
for (Entity entity : handler.getEntities()) {
// do stuff
}
handler.saveEntity(this);
}
}
public class Player<T extends PlayerHandler<Player>> extends Entity</*error here*/T> {}
public class EntityHandler<T extends Entity> {
private List<T> entities;
public void saveEntity(T entity) {
// do stuff
}
public List<T> getEntities() {
return entities;
}
}
public class PlayerHandler<T extends Player> extends EntityHandler<T> {}
Error: type argument T is not within bounds of type-variable T
Case 2:
public class Entity<T extends EntityHandler<? extends Entity>> {
protected T handler;
public void remove() {
for (Entity entity : handler.getEntities()) {
// do stuff
}
handler.saveEntity(/*error here*/this);
}
}
public class Player<T extends PlayerHandler<? extends Player>> extends Entity<T> {}
public class EntityHandler<T extends Entity> {
private List<T> entities;
public void saveEntity(T entity) {
// do stuff
}
public List<T> getEntities() {
return entities;
}
}
public class PlayerHandler<T extends Player> extends EntityHandler<T> {}
Error: incompatible types: Entity cannot be converted to capture#1 of ? extends Entity
Question: why does the enhanced for loop compile and it doesn't throw a compile error similar to the one above?
In first case you've marked error in wrong place. It's here:
public class Player<T extends PlayerHandler<Player>> extends Entity<T //here> {}
Error:(20, 73) java: type argument T is not within bounds of type-variable T
And it's quite easy - Entity can be parameterized only with classes which extend EntityHandler.
In second case your for compiles because of erasure, so basically getEntities returns just List of something.
As for saveEntity error, there you are trying to pass capture<? extends Entity but method expects to have Entity<T>, which is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With