-
[Java] How to implement hash? Map or Hashmap?카테고리 없음 2015. 9. 15. 21:04
When I wanted to write code with a "hash table" that I learned from a data structure book, I was not sure what java class to use... I did some research and found that Hashmap is my best bet for most of my purposes. Hash table is a great invention. (source: http://www.quora.com/Who-invented-hash-tables)
I do not write multi-threaded application. And I just want to put items in the data structure and find things quickly with key...
You can declare a Hashmap object as follows:
Hashmap<String, String> hm = new Hashmap<String, String>();
You can change "String" to any type you want.
Next, you may want to put your key, value pairs into the hm obect as follows:
hm.put("KeyString1", "ValueString1");
If you find some value with your key value, you can do is as follows:
String s = hm.get("KeyString1");
Then s will get "ValueString1".
Finally, sometimes I want to iterate all the items in the Hashmap object, even though it is not a list. We can do that by using Iterator object as follows:
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String keyStr = pair.getKey();
String valueStr = pair.getValue();
}
Hope this will help you...