3

对于分配,我必须创建和操作MyArrayList<E>java.util.ArrayList<E>. 如果满足要求,我需要访问highScore对象内部的变量GameEntry,以便将条目添加到 aMyArrayList中,但我似乎做不到?

游戏入口类

public class GameEntry
{   public String name;
    public int highScore;
    public String handle;

    public GameEntry()
    {   name = this.name;
        highScore = this.highScore;
        handle = this.handle;
    }

    public GameEntry(String n, int hs, String h)
    {   name = n;
        highScore = hs;
        handle = h;
    }

    public String getName() { return name; }
    public int getHScore() { return highScore; }
    public String getHandle() { return handle; }

    public String toString() {
        return "(" + handle + ", " + name + ": " + highScore + ")";
    }
}

MyArrayList 类

public class MyArrayList<E> extends java.util.ArrayList<E>
{   private int numEntries = 0;
    public MyArrayList() { super(); }
    public MyArrayList(int capacity) { super(capacity); }

    public boolean isListEmpty() { return this.isEmpty(); }

    // add new score to MyArrayList (if it is high enough)
    public void addInOrder(GameEntry e) {
        int newScore = e.getHScore();

        // is the new entry e really a high score?
        if(numEntries<this.size() || newScore > this.get(numEntries-1).getHScore())
        //ERROR: cannot find symbol - method getHScore()
        // ...rest of addInOrder code...
        }
    }    
}
4

1 回答 1

0

您收到此错误是因为this.get(numEntries - 1)将返回一个泛型,并且程序将无法使用getHScore()它,除非您将其转换为GameEntry.

您可以通过检查它是否是一个GameEntry对象instanceof然后强制转换它来做到这一点:

public void addInOrder(GameEntry e) {
    int newScore = e.getHScore();

    // is the new entry e really a high score?
    if (this.get(numEntries - 1) instanceof GameEntry) {

        GameEntry ge = (GameEntry) this.get(numEntries - 1); //Cast to GameEntry
        if(numEntries<this.size() || newScore > ge.getHScore()) {
            //Do whatever
        }
    }
   //Add behavior for when it is NOT an instance of GameEntry
}

可能有更好的方法来实现你想要的行为addInOrder,但我想我会回答你的字面问题,为什么getHScore()不适合你。

于 2020-03-11T14:14:20.317 回答