A map is an interface in the java.util package which stores the association between key and its corresponding value. A map cannot contain duplicate keys; each key can map to at most one value Map differs from array in a way that we can store a value at a particular index in arrays but a Map determines the index itself and does this based on the value on the key.
HASHMAP is a class which implements the map interface.
Hash map is a data structure which uses a hash function to map identifying values, known as keys (e.g., a person’s name) to their associated values (e.g., their telephone number).
The hash function transforms the key into the index (the hash) of an array element where the corresponding value is to be sought.
Take for instance the case of a phonebook. you can have a map where the keys are phone numbers and the value is the name of the person..
Given a key you can find its value.
Ex.[“key”, “value”]=[“88028”,”vinay”]
With the given key value i.e 88028 one can find its value….. which is vinay.
Take another example…..
import java.util.Map; import java.util.HashMap; public class Map_example { Map<Integer, String> addPhoneNum = new HashMap<Integer, String>(); public void addPhoneNum(Integer phonenumber, String name) { addPhoneNum.put(phonenumber, name); } public String getName(Integer phonenumber) { return addPhoneNum.get(phonenumber); } public static void main(String[] args) { Map_example m1 = new Map_example(); m1.addPhoneNum(9911538992 "vinay"); System.out.println( m1.getName(9911538992)); }
Main features of HASHMAP are.
• HashMap is a library class in Java.
• It is already implemented, hence can be used immediately HashMap is a library class in Java.
• HashMap stores only object references. That’s why, it’s impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.
• For multi-theaded(synchronized) array class use Hashtable (java.lang.Hashtable)
The two most important HashMap’s methods are:
• get( Object key ) –this method returns the value associated with specified key in this hash map, or null if there is no value for this key
• put(K key, V value) – this method associates the specified value with the specified key in the map.
Internally a HashMap maintains an array. To have the HashMap work efficiently, the array must be large enough so that the key/value pairs are well-distributed and the performance is not affected. Therefore, the HashMap maintains two (customizable) variables :
1. Capacity
2. LoadFactor.
The capacity is the length of the internal array whereas the LoadFactor controls when the capacity should be increased.