HashMap in java
Java
HashMap is a part of collection since jdk 1.2 versions. HashMap implements the
Map interface and extends AbstractMap class. HashMap stores data in key &
value pairs.
HashMap
uses Hashing technique for storing key and value pair in java.
The HashMap class
is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls.
HashMap - Here k means Key which is any data type
V means Value of any data types
HashMap in Java - techfloaters |
HashMap class Declaration
public class
HashMap extends
AbstractMap
implements
Map, Cloneable, Serializable {
Features
of HashMap class
1] HashMap stores unique key only. Duplicate key not
allowed if we try to enter then recent one get override by previous one.
2] HashMap uses hashing mechanism to store unique
element.
3] HashMap
does not maintain insertion order
because element are stored on the basis of hashing technique.
4] HashMap
allows multiple null values but only
one null key.
5] HashMap
class is not thread safe, it means
it is non synchronized.
Constructor
and Description
HashMap<K, V> hs = new
HashMap()
This is default constructor which constructs
an empty HashMap with the default initial capacity (16) and the default load
factor (0.75).
HashMap<K, V> hs = new
HashMap(int initialCapacity)
Constructs an empty HashMap with the
specified initial capacity and the default load factor (0.75).
HashMap<K, V> hs = new
HashMap(int initialCapacity,
float loadFactor)
Constructs an empty HashMap with the
specified initial capacity and load factor.
HashMap<K, V> hs = new
HashMap(Map m)
Constructs a new HashMap with the
same mappings as the specified Map.
Constructs a new
set containing the elements in the specified collection.
Java HashMap
Example
package com.vr.techfloaters;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
// This is how to
declare HashMap
HashMap hm = new HashMap<>();
//Adding elements
to HashMap
hm.put(50, "java");
hm.put(26, ".Net");
hm.put(20, "php");
hm.put(null, null);
hm.put(25, ".Net");
//Get values based
on key
System.out.println(hm.get(20));
//Remove key and
values based on key
System.out.println(hm.remove(25));
//Iterating the
element in HashMap
Set<
Entry > set = hm.entrySet();
Iterator> itr = set.iterator();
while(itr.hasNext())
{
Entry entry = itr.next();
System.out.println(entry.getKey() +" : "+entry.getValue());
}
}
}
Output
php
.Net
null : null
50 : java
20 : php
26 : .Net
From above output we can see duplicate key are not allowed and also
insertion order is not followed.
0 comments:
Post a Comment