将超类转换为泛型T

时间:2019-04-15 13:08:24

标签: java android generics

我最近开始在项目中使用通用方法。我正在一个国际象棋项目中,每个零件类都扩展到 Pieces.java

Diagram of my pieces package

Player.java 中,我添加了以下代码:

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

但是,现在,IntelliJ给我一个警告,“未经检查的从“片断”转换为T。 即使当我提到 ,而pieces数组的所有元素都是Pieces的子类时,IntelliJ也会向我发出警告:“从 Pieces 到T的未经检查的转换”。我应该如何解决这个问题。

请不要将其标记为重复,因为其他问题的答案对我没有帮助。

0 个答案:

没有答案