This question already has an answer here:

I have recently started using generic methods in my projects. I am working on a chess project where every piece class extends to Pieces.java.

Diagram of my pieces package

And in the Player.java, I have added this code:

public class Player {
    Pieces[] pieces = new Pieces[16];
    Player() {
        …
        init();
    }
    private void init() {
        //initialize pieces array with all pieces.
        pieces[0] = new Pawn(new Point(6, 0), this);
        pieces[1] = new Pawn(new Point(6, 1), this);
        pieces[2] = new Pawn(new Point(6, 2), this);
        pieces[3] = new Pawn(new Point(6, 3), this);
        pieces[4] = new Pawn(new Point(6, 4), this);
        pieces[5] = new Pawn(new Point(6, 5), this);
        pieces[6] = new Pawn(new Point(6, 6), this);
        pieces[7] = new Pawn(new Point(6, 7), this);
        pieces[8] = new Rook(new Point(7, 0), this);
        pieces[9] = new Knight(new Point(7, 1), this);
        pieces[10] = new Bishop(new Point(7, 2), this);
        pieces[11] = new Queen(new Point(7, 3), this);
        pieces[12] = new King(new Point(7, 4), this);
        pieces[13] = new Bishop(new Point(7, 5), this);
        pieces[14] = new Knight(new Point(7, 6), this);
        pieces[15] = new Rook(new Point(7, 7), this);
    }
    public <T extends Pieces> T getPiece(Point point) {
        for(Pieces piece: pieces) {
            if(piece.isAlive() && piece.getCurrentPoint().equals(point))
                return (T)piece;
        }
        return null;
   }
}

But now, IntelliJ gives me a warning, "Unchecked cast from "Pieces" to T. Even when I mentioned that and all the elements of pieces array is a subclass of Pieces, even then IntelliJ gives me a warning: "Unchecked cast from Pieces to T". How am I supposed to fix this.

Please do not mark this as duplicate because the answer of other questions have not helped me.

Related posts

Recent Viewed