I was working on a part of an in-house library today and wanted to improve some things by adding basic generics to our "Game" class.
Here is the stripped down version of the, now changed, game class:
public abstract class Game<G extends GamePlayer> {
private final List<G> players;
public Game() {
this.players = new LinkedList<>();
}
public Collection<G> getPlayers() {
return players;
}
}
Pretty standard, I know. But when I wanted to use the getPlayers() method in a game module like this: for (GamePlayer player : game.getPlayers())
All it gave me was an error that the return type equals "Collection<Object>
" instead of "Collection<G>
".
All other functions I have (like G getPlayer(String name)
) return the correct type, but not the getPlayers function.
I really want to avoid implementations of this library cast their players to things like
MyGamePlayer player = (MyGamePlayer) myGame.getPlayer("dummy")
.
What did I do wrong with the generics?
Edit:
Here is the class that contains the for
loop:
public class GiftTask implements Runnable {
private final Game game;
private final Item[] items;
public GiftTask(Game game, List<Item> itemList) {
this.game = game;
this.items = itemList.toArray(new Item[itemList.size()]);
}
@Override
public void run() {
for (GamePlayer player : game.getPlayers()) { // This line has the error
player.getInventory().addItem(items);
}
}
}
you should use this:
private final Game<GamePlayer> game;
you're using the raw type of Game
.
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