HashMap class is used to implement Map interface. The value of HashMap is stored using get() and put(). HashMap provides key-value access to data. HashMap is almost equal to HashTable, the only difference is that HashMap allows null value and is unsynchronized. HashMap does not guarantee the order of the map. This means that it is not necessary that the order in which the elements are read by Iterator is same to the order in which they were added.
HashMap class is used to implement Map interface. The value of HashMap is stored using get() and put(). HashMap provides key-value access to data.
HashMap is almost equal to HashTable, the only difference is that HashMap allows null value and is unsynchronized.
HashMap does not guarantee the order of the map. This means that it is not necessary that the order in which the elements are read by Iterator is same to the order in which they were added.
Declaration:
HashMap
Map
If you use Map
Methods | Description |
void clear( ) | deletes the key/value pair |
boolean containsKey(Object key) | Checks whether the specified key mapping in a map is available or not and returns True if it does otherwise, returns false. |
boolean containsValue(Object value) | Checks whether the specified value is mapped with one or mote keys or not. |
Set entrySet( ) | Returns a Set that contains the entries in the map. This method provides a set-view of the invoking map. |
boolean equals(Object object) | Checks whether the object is a Map and have the same entries or not. |
Object get(Object k) | Returns the value associated with the key k or returns null |
boolean isEmpty( ) | Checks whether the invoking map is empty or not. |
Set keySet( ) | This method Returns a Set that contains the keys in the invoking map. |
Object put(Object k, Object v) | This method overwrites any previous value associated with the key or Returns null if the key did not already exist. |
void putAll(Map m) | Cpies all the entries from specified map m into this map. |
Object remove(Object k) | Removes the entry for specified key k from this map. |
int size( ) | Returns the number of key/value pairs in the map. |
Collection values( ) | This method provides a collection-view of the values in the map. |
Example of Hashmap in Java:
package net.roseindia.java; import java.util.HashMap; public class HashMapExample { public static void main(String[] arr) { /* Create object of HashMap */ HashMapobMap = new HashMap (); /* Add value in HashMap */ obMap.put(new Integer(1), "Bharat"); obMap.put(new Integer(2), "Gyan"); obMap.put(new Integer(4), "Vrishti"); obMap.put(new Integer(3), "Sarika"); obMap.put(new Integer(5), "Rohit"); obMap.put(new Integer(6), "Parineeta"); /* Display value of HashMap */ System.out.println("Elements in HashMap : \n" + obMap); } }
Output:
Elements in HashMap: {1=Bharat, 2=Gyan, 3=Sarika, 4=Vrishti, 5=Rohit, 6=Parineeta}