2
2
.
.
6
6
.
.
3
3
H
H
a
a
s
s
h
h
M
M
a
a
p
p
I
I
n
n
f
f
o
o
[
[
C
C
]
]
HashMap
is Class that contains variable collection of key-value pairs
can't contain duplicate keys
Both keys and values can be: Object, Primitive Data Type or null value.
There are two versions of HashMap Class
HashMap is Non-Generic version of the Class (assumes that both key and value are just Objects)
HashMap<K, V> is Generic version of the Class (you can specify Data Type for key and values)
It is advisable to use Generic version because of Data Type checking & to avoid manual casting when retrieving elements.
When adding elements you can use Primitive Data Types but they will be converted into Non-Primitive Data Types.
When retrieving elements Non-Primitive Data Types are automatically cast to Primitive Data Types if needed and possible.
Use HashMap instead Hashtable since
it allows null values for both keys and values
it's iterator is fail-safe throwing Exception if another thread tries to modify collection "structurally" while iterating
it is not thread-safe making it faster and giving you an option to synchronize it or not
Test.java
import java.util.HashMap;
public class Test {
public static void main (String arg[]) throws Exception {
//PUT ELEMENTS.-------------------------------------------
HashMap hashmap = new HashMap();
hashmap.put("key" , "element" ); //Add key-value pair.
hashmap.put("age" , 33 );
hashmap.put(new Integer(34) , false );
hashmap.put(1 , new Character('A') );
//GET ELEMENTS.-------------------------------------------
String name = (String ) hashmap.get ("key" );
int age = ( (Integer ) hashmap.get ("age" ) ).intValue ();
boolean flag = ( (Boolean ) hashmap.get (new Integer(34) ) ).booleanValue ();
char stuff = ( (Character) hashmap.get (1 ) ).charValue ();
//STATISTICS.---------------------------------------------
boolean containsElement = hashmap.containsValue("element");
boolean containsKey = hashmap.containsKey ("key" );
boolean isEmpty = hashmap.isEmpty ( );
int size = hashmap.size ( );
String removed = (String) hashmap.remove ("key" );
hashmap.clear ( );
//DISPLAY STATISTICS.-------------------------------------
System.out.println ("Contains 'element' = " + containsElement);
System.out.println ("isEmpty = " + isEmpty );
System.out.println ("size = " + size );
System.out.println ("removed element = " + removed );
}
}