Reputation: 3
i have quick question, what I am trying to do here is to, get the Student from HashMap and adds a double mark to Student's mark.
lets say i have class called Student and Student class has method called addToMark() and Hashmap called theStudent = new HashMap<String, Student>
.
public void addExtraMark(String studentNumber, double mark) {
if(stuentNumber != null && mark >= 0) {
Student extraMark = theStudent.get(studentNumber);
extraMark.addToMark(mark)};
}
}
my question is, does mark adds to hashmap? automatically? or do i have to use
theStudent.put(studentNumber, extraMark);
on the bottome of my code?
Upvotes: 0
Views: 70
Reputation: 31689
In this code:
Student extraMark = theStudent.get(studentNumber);
extraMark.addToMark(mark)}};
If the studentNumber
doesn't exist in the hash map, get
returns null
. Then extraMark.addToMark
will throw a NullPointerException
.
So you have to check yourself, e.g.:
Student extraMark;
if (theStudent.containsKey(studentNumber)) {
extraMark = theStudent.get(studentNumber);
} else {
extraMark = new Student(.......);
theStudent.put(studentNumber, extraMark);
}
extraMark.addToMark(mark);
or you do the get
first and check the result for null
.
Note: I've assumed that your question "does mark adds to hashmap" meant "would it add a new student to the hashmap if it weren't already there", but after rereading your question, I'm not clear on what you meant.
Upvotes: 1
Reputation: 4191
Since Student extraMark
is a reference to that Student, anything you do to the reference will be reflected in the HashMap.
No, you do not have to make the call:
theStudent.put(studentNumber, extraMark);
Upvotes: 2