我正在尝试为我的国际象棋游戏设计一种撤消/重做机制。.我决定使用将在ArrayList上构建的堆栈数据结构。.我也希望我的UndoStack和RedoStack类应该是单例的。越来越

method does not override or implement a method from a supertype

pop() in UndoStack cannot implement pop() in IStackable
  return type Move is not compatible with cgas5.Move
  where Move is a type-variable:
    Move extends Object declared in class UndoStack


错误..

这是我的IStackable接口:

package cgas5;


public interface IStackable {

    abstract public Move pop();

    abstract public void push(Move m);

}


和我的UndoStack类

package cgas5;

import java.util.ArrayList;

public class UndoStack<Move> extends ArrayList<Move> implements IStackable {

    UndoStack undoStack;

    private UndoStack() {
        undoStack = new UndoStack();
    }

    public UndoStack getUndoStack() {
        if (undoStack == null) {
            undoStack = new UndoStack();
        }
        return undoStack;
    }

    @Override
    public Move pop() {
        Move m = get(size() - 1);
        remove(size() - 1);
        return m;

    }

    @Override
    public void push(Move m) {
        add(m);
    }
}


并且如果需要我的Move类:

package cgas5;

public class Move {
    private Piece pieceToMove;
    private Square currentSquare;
    private Square targetSquare;
    private Piece capturedPiece;
    private Piece promotedPiece;

    public Move(){

    }

    public Move(Piece pieceToMove, Square currentSquare, Square targetSquare){
        this.pieceToMove = pieceToMove;
        this.currentSquare = currentSquare;
        this.targetSquare = targetSquare;
    }

    public Piece getPieceToMove() {
        return pieceToMove;
    }

    public void setPieceToMove(Piece pieceToMove) {
        this.pieceToMove = pieceToMove;
    }

    public Square getCurrentSquare() {
        return currentSquare;
    }

    public void setCurrentSquare(Square currentSquare) {
        this.currentSquare = currentSquare;
    }

    public Square getTargetSquare() {
        return targetSquare;
    }

    public void setTargetSquare(Square targetSquare) {
        this.targetSquare = targetSquare;
    }

    public Piece getCapturedPiece() {
        return capturedPiece;
    }

    public void setCapturedPiece(Piece capturedPiece) {
        this.capturedPiece = capturedPiece;
    }

    public Piece getPromotedPiece() {
        return promotedPiece;
    }

    public void setPromotedPiece(Piece promotedPiece) {
        this.promotedPiece = promotedPiece;
    }

}


提前致谢..

最佳答案

这就是问题:

public class UndoStack<Move> extends ArrayList<Move>


那是使用Move作为泛型类型参数,而实际上您根本不需要泛型-您只想使用Move作为ArrayList<E>的类型参数。你要:

public class UndoStack extends ArrayList<Move>


那应该可以解决问题-尽管我个人强烈建议在这里使用组合而不是继承。 (换句话说,使您的UndoStack类型包含一个ArrayList<Move>-或类似名称-而不是对其进行子类化。)

此外,这永远行不通:

UndoStack undoStack;

private UndoStack() {
    undoStack = new UndoStack();
}


这意味着要创建一个UndoStack,您需要创建另一个UndoStack ...您如何期望这种情况发生?当前,您将获得一个堆栈溢出异常...为什么根本需要该变量?

10-06 01:51