Java,如何避免“可能尚未初始化”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7969851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:15:49  来源:igfitidea点击:

Java, how can I avoid "might not have been initialized"

javaarraylistinitialization

提问by vedran

I have a HashMap called examListwhich stored exam grades of each course a student took. The key of this hashmap is courseID, and the value is an array list gradeListwhich contains all grades a student got in a course. The problem is as follows:

我有一个名为 HashMap 的 HashMap examList,它存储了学生参加的每门课程的考试成绩。这个 hashmap 的键是courseID,值是一个数组列表gradeList,其中包含学生在课程中获得的所有成绩。问题如下:

// 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.");
    }
}

As you can see I first define gradeList, but I do not yet initialize it. Under IF I check if student has already done this exam before. If he hasn't then new entry is created for hashmap, and gradeList is finally initialized. Under ELSE (where, it is considered that there is an element with gradeList already initialized) I just add new grade. However, that seems to be the problem. I can't compile it because program presumes that gradeList is not yet initialized here. So, how can I fix this? Or can I avoid it (since logically, gradeList will always be initialized under ELSE) through error handling, of which I know little about?

正如你所看到的,我首先定义了gradeList,但我还没有初始化它。在 IF I 检查学生之前是否已经完成此考试。如果他还没有,则为 hashmap 创建新条目,并最终初始化 GradeList。在 ELSE 下(这里认为有一个已经初始化了 gradeList 的元素)我只是添加了新的成绩。然而,这似乎是问题所在。我无法编译它,因为程序假定这里的 gradeList 尚未初始化。那么,我该如何解决这个问题?或者我可以通过错误处理来避免它(因为从逻辑上讲,gradeList 将始终在 ELSE 下初始化),而我对此知之甚少?

回答by Bhesh Gurung

ArrayList<Integer> gradeList = null;

In your case, it's better to do something as follows:

在您的情况下,最好执行以下操作:

List<Integer> gradeList = examList.get(courseID);
if(gradeList == null) {
    gradeList = new ArrayList<Integer>();
    //... do something
} else {
    //... do something else
}

回答by Reid Mac

just initialize gradeList when you create the variable.

创建变量时只需初始化gradeList。

ArrayList<Integer> gradeList = new ArrayList<Integer>();

or set it to null

或将其设置为空

ArrayList<Integer> gradeList = null;

回答by maerics

Assign nullin its declaration:

null在其声明中赋值:

ArrayList<Integer> gradeList = null;

回答by óscar López

When you declare the ArrayList, simply write gradeList = null. Or even better, to avoid NullPointerExceptions, initialize it on the spot, like this: ArrayList<Integer> gradeList = new ArrayList<Integer>();

当您声明 ArrayList 时,只需编写gradeList = null. 或者更好的是,为了避免 NullPointerExceptions,就地初始化它,像这样:ArrayList<Integer> gradeList = new ArrayList<Integer>();

回答by JB Nizet

If the map contains the key, then the value for this key is your gradeList. Just add this line under else if ( examList.containsKey(courseID)) {:

如果地图包含键,则该键的值就是您的成绩列表。只需在下面添加这一行else if ( examList.containsKey(courseID)) {

gradeList = examList.get(courseID);

Note that naming a map examListis pretty confusing. Why not examMap? Also note that you could just use else {instead of else if ( examList.containsKey(courseID)) {: either the map contains the courseID, or it doesn't; there's no other possibility. Finally, you'll also have to fix the next line of code, because it's not correct.

请注意,命名地图examList非常令人困惑。为什么不examMap呢?另请注意,您可以只使用else {而不是else if ( examList.containsKey(courseID)) {:地图包含 courseID,或者不包含;没有其他可能。最后,您还必须修复下一行代码,因为它不正确。