我有一个名为examList的HashMap,它存储了学生参加的每门类(class)的考试成绩。该哈希图的关键字是courseID,其值是一个数组列表gradeList,其中包含学生在类(class)中获得的所有成绩。问题如下:

// Add a new course exam listing
// where each course exam can be done a max 5 times
protected void addExam(String courseID, int grade) {
    ArrayList<Integer> gradeList;
    // First check if course is in the list, if not add it
    if ( !examList.containsKey(courseID) ) {
        gradeList = new ArrayList<Integer>();
        examList.put(courseID, gradeList);
        examList.get(gradeList.add(grade));
    // If course is already on the list, check if max number of attempts has been reached, if not add new grade
    } else if ( examList.containsKey(courseID)) {
        if ( gradeList.size() <= 5 )            // THIS IS WHERE ERROR OCCURES
            examList.get(gradeList.add(grade)); // HERE ALSO
        else
            System.out.println("Maxim number of attempts has been reached.");
    }
}

如您所见,我首先定义了gradeList,但尚未对其进行初始化。在IF下,我检查学生之前是否已经做过这项考试。如果还没有,那么将为hashmap创建新条目,并最终初始化gradeList。在ELSE下(其中,有一个已经初始化了gradeList的元素),我只是添加新的成绩。但是,这似乎是问题所在。我无法编译它,因为程序认为此处的gradeList尚未初始化。
那么,我该如何解决呢?还是我可以通过错误处理来避免它(从逻辑上讲,gradeList将始终在ELSE下初始化),对此我几乎一无所知?

最佳答案

ArrayList<Integer> gradeList = null;

在您的情况下,最好执行以下操作:
List<Integer> gradeList = examList.get(courseID);
if(gradeList == null) {
    gradeList = new ArrayList<Integer>();
    //... do something
} else {
    //... do something else
}

09-12 23:17