java - I am using HashMap in HashMap but I need to use ArrayList as value as well. I'm having trouble giving value -
i using hashmap in hashmap need use arraylist value well. i'm having trouble giving value
private hashmap<string, hashmap<string, arraylist<string>>> languages_hashmap = new hashmap<string, hashmap<string, arraylist<string>>>(); public void addvalue (string language, string code , string value, boolean isstringarray) { hashmap<string,arraylist<string>> dictionary = languages_hashmap.get(language); if (dictionary == null) { dictionary = new hashmap<string,arraylist<string>>(); } dictionary.put(code, value ); languages_hashmap.put(code, dictionary); }
first of need objects in life, nesting many maps , collections code smell.
there 2 different concepts in code :
- a
dictionary
holdsvalues
eachcode
- another thing associates
dictionary
language. i'll calltranslator
, should find name more suitable
separating responsibilities make code more readable, , allow test each case separately :
public class translator { // reference interface instead of concrete types whenever can // (i.e. use map instead of hashmap) private map<string, dictionary> dictionaries = new hashmap<>(); public void addvalue(string lang, string code, string value) { dictionaries.get(lang).add(code, value); } public list<string> getvalue(string lang, string code) { return dictionaries.get(lang).get(code); } public void adddictionary(string lang, dictionary dictionary) { dictionaries.put(lang, dictionary); } } public class dictionary { // same here, use interfaces list or map instead of implementations map<string, list<string>> values = new hashmap<>(); public void add(string code, string value) { list<string> list = values.get(code); // if there no previous value code, // create new list of values if (list == null) { list = new arraylist<>(); values.put(code, list); } list.add(value); } public list<string> get(string code) { return values.get(code); } }
Comments
Post a Comment