The HashMap in Java is one of the most popular Collection class among Java programmers. After my article on How HashMap works in Java, which describes theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with some fundamental HashMap examples, but couldn't do that earlier and it was slipped. The HashMap is a data structure, based on hashing, which allows you to store an object as key value pair, an advantage of using HashMap is that you can retrieve object on constant time i.e. O(1) if you know the key. The HashMap class implements Map interface and supports Generics from Java 1.5 release, which makes it type safe. There are a couple of more Collections, which provides similar functionalities like HashMap, which can also be used to store key value pair. Hashtable is one of them, but Hashtable is synchronized and performs poorly in a single threaded environment. See Hashtable vs HashMap for complete differences between them. Another one, relatively new is ConcurrentHashMap, which provides better performance than Hashtable in a concurrent environment and should be preferred. See the difference between ConcurrentHashMap and HashMap for detail differences.
In this Java tutorial, we will see different examples of HashMap, like adding and removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map and various other examples, which we used frequently.
Java HashMap Example

Before going to see these examples, few things to note about Java HashMap.It’s not synchronized, so don't share your HashMap among multiple threads. Another common cause of error is clearing Map and reusing it, which is perfectly valid in a single threaded environment but if done in a multi-threaded environment can create subtle bugs.
Read more: http://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html#ixzz4RH7nZRvc
Read more: http://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html#ixzz4RH7ZGf79

No comments:
Post a Comment