Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

// 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?

like image 457
vedran Avatar asked Nov 01 '11 16:11

vedran


3 Answers

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
}
like image 58
Bhesh Gurung Avatar answered Nov 15 '22 06:11

Bhesh Gurung


just initialize gradeList when you create the variable.

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

or set it to null

ArrayList<Integer> gradeList = null;
like image 44
Reid Mac Avatar answered Nov 15 '22 05:11

Reid Mac


Assign null in its declaration:

ArrayList<Integer> gradeList = null;
like image 24
maerics Avatar answered Nov 15 '22 05:11

maerics