Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> returns an object collection

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);
            }
        }

    }
like image 904
spaceemotion Avatar asked Mar 31 '14 10:03

spaceemotion


1 Answers

you should use this:

private final Game<GamePlayer> game;

you're using the raw type of Game.

like image 156
ikh Avatar answered Oct 20 '22 16:10

ikh