0

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?

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.