Tuesday, 15 May 2012

java - HashMap of ArrayList, String is not working properly? -



java - HashMap of ArrayList<String>, String is not working properly? -

so , want create map of lists of strings strings, cannot work properly:

this code have done, , until can find out why, cannot progress:

map<list<string>, string> test = new hashmap<list<string>, string>(); test.put( new arraylist<string>(), "s1"); test.put( new arraylist<string>(), "s2"); test.put( new arraylist<string>(), "s3"); system.out.println(test.size());

i 1, should 3!! why 1 object getting added when made 3 calls, 3 separate objects? know danger of accidentally adding in same object collection, created new arraylist each put, creating total brand new object.

so why there 1 object in map then? thanks!

try this:

map<string,list<string>> test = new hashmap<string,list<string>>(); test.put("s1", new arraylist<string>()); test.put("s2", new arraylist<string>()); test.put("s3", new arraylist<string>()); system.out.println(test.size());

note map key-value relation. reason, may want utilize string key , arraylist values, instead of other way around. way, if add together 3 different strings, each 1 have different hash value (hashcode). thus, have 3 different keys in map.

note that:

put

public object put(object key, object value) associates specified value specified key in map. if map contained mapping key, old value replaced.

this why getting 1, instead of 3, because adding same object new arraylist<string>().

take in more detail class hashm specifications.

java string arraylist hashmap

No comments:

Post a Comment