collections - How do I create a dictionary in Java? -
i curious how create dictionary in java. know python had dictionary setup similar dictionary = {"key": "something"}
. know there other ways in java, such creating 2 synchronized lists , using same position in each list mimic dictionary.
arraylist<object> keys = new arraylist<object>(); arraylist<object> values = new arraylist<object>(); public void add(object key, object value){ keys.add(key); values.add(value); } // , subsequent return function public object getvalue(object key) { return values.get(keys.indexof(key)); }
however, screams me bad programming. there simpler syntax single statement? questions asked subject closed and, consequently, of little help.
java uses hashmaps instead of dictionaries.
some other maps include treemap. difference in backend (one uses hash table, other uses red-black tree)
example:
import java.util.hashmap; import java.util.iterator; import java.util.map; import java.util.set; .... map<string,string> mmap = new hashmap<string, string>(); mmap.put("key", "something"); iterator iter = mmap.entryset().iterator(); while (iter.hasnext()) { map.entry mentry = (map.entry) iter.next(); system.out.println(mentry.getkey() + " : " + mentry.getvalue()); }
Comments
Post a Comment