sayid jetzenden sayid jetzenden - 4 months ago 25
Java Question

Java store values in map

Let class getChoice implement a LinkedHashMap.
Let a method addCh implement the choice.put.
Let some classes choice1 and choice2 extend class choice and passing elements to getChoice.map. Each time I'm passing an object to Map it seems not to update but rather to be created again with the same name. I need to store all elements first in map and then save them into a file. How can I do that? My code so far.

public class GetChoice{

Map<String, String> choice = new LinkedHashMap<String, String>();

public void addChoice(SomeClass obj1, SomeOtherClass obj2) {

if (obj2 instanceof Choice1) {
this.choice.put(obj2.toString(), "choice1");
} else if (obj2 instanceof Choice2) {
this.choice.put(obj2.toString(), "choice2");
} else {
//sysout not found
}

System.out.println("\n" + choice);
}


Edit: I handled it by declaring the Map as static, after @dasblinkenlight mentioned it is created each call.
Thanks a lot guys.

Answer

choice map is an instance field of the GetChoice object. Every time you make a new GetChoice a brand-new map with no data is created.

In order to persist the data in the map across invocations of addChoice you need to create your GetChoice object once, and then call addChoice on that same object multiple times.