Hashmap adding | SoloLearn: Learn to code for FREE!

-2

Hashmap adding

for exemple: i have a hashmap donations. that stores the name of the donator and the amount: donations.put("bob";150); donations.put("sarah";100); System.out.println("bob"); 150 will return. if i were to add: donations.put("bob";100); that it will keep adding money to the total amount that bob donated right?

1/9/2017 2:26:56 PM

Stein Charlier

2 Answers

New Answer

+2

you have to do it like this if (donations.containsKey("bob")) donations.put("bob", donations.get("bob") + 100); else donations.put("bob", 100); and your syntax for adding key/value is wrong they should be separated by comma also for getting the value you need to do it like this System.out.println(donations.get("bob")); //returns the value

+2

Well... If you use the same key to define a new value in Hashmap it will override the old value of that key. So for your example, you should do the following: int oldValue = donations.get("bob"); donations.put("bob", oldValue+100/*value to add*/); I suggest you to write a method to do this: public void addMoneyToPerson(String person, int value){ donations.put(person, donations.get(person)+ value); //more compact version }