为什么不添加方法接受我的输入?

时间:2014-08-18 00:51:51

标签: java arraylist append

到目前为止,这是我有问题的代码,假设其他所有内容都已完成:

public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score) {
    // write your code after this line

    int i = 0;
    for (GameRecord gr : highScoreRecords){
        if (gr.getScore() >= gr.getScore()){
            highScoreRecords.add(i+(gr.getLevel()-level),(Object) new GameRecord(name, level, score)); /*
            *adds the new GameRecord in at the (i+gr's level - level)th iteration.
            *note it does this because of the assumtion that highScoreRecords is ordered becuase of only using this function
            */
           break; //no more need to continue the loop
        }


        i += 1;
    }
    return highScoreRecords;
}

您可能已经注意到,我的代码是课程的一部分,所以这就是为什么我假设所有其他实现都是完美的。

2 个答案:

答案 0 :(得分:2)

您正在传递GameRecord[] highScoreRecords数组,

但调用List方法add - 这在Array上不存在。您应该收到编译错误。

如果您确定该阵列具有插入容量,那么您可以

highScoreRecords[i+(gr.getLevel()-level)] = new GameRecord(name, level, score);

但我想您最好使用List ArrayList,并保留现有代码。为此,您将List传递给方法而不是Array。

答案 1 :(得分:1)

Java数组不是动态数据结构,

highScoreRecords.add(i+(gr.getLevel()-level),
    (Object) new GameRecord(name, level, score));

我想你想要

// Using a List.
GameRecord[] updateHighScoreRecords(List<GameRecord> highScoreRecords, 
    String name, int level, int score) {

此外,请勿投放到Object。这是raw-type