HashMap vs TreeMap vs HashTable vs concurrentHashMap values and keys

import java.util.*;
import java.util.concurrent.*;

public class StaticVsNormalVsNo_Imports{
public static void main(String[] args)throws Exception{
ArrayList<Integer> arraylist=new ArrayList<Integer>();
System.out.println(arraylist.add(10));
System.out.println(arraylist);

//Key shouldn’t be null in treemap
//If we put two keys similar it will ovverride
//multiple Null values are allowed
TreeMap<String,String> treeMap=new TreeMap<String,String>();
treeMap.put(“null”,null);
treeMap.put(“null1”,null);
treeMap.put(“null”,”nuller”);
treeMap.put(“null2″,null);
System.out.println(treeMap);

//one key can be null
//If we put two keys similar it will ovverride
//Multiple null values allowed
HashMap<String,String> hashMap=new HashMap<String,String>();
hashMap.put(null,null);
hashMap.put(null,”null1”);
hashMap.put(“null1”,null);
hashMap.put(“null2”,null);
hashMap.put(“null3″,null);
hashMap.put(null,”nuller”);
System.out.println(hashMap);

//No nulls as keys as well as values too
Hashtable<String,String> hashTable=new Hashtable<String,String>();
hashTable.put(“null”,”null-1″);
hashTable.put(“null1″,”null”);
hashTable.put(“null1″,”nuller”);
System.out.println(hashTable);

//No nulls as keys as well as values too
//thread safe
Map<String,String> conMap= new ConcurrentHashMap<String,String>();
conMap.put(“null1″,”null”);
conMap.put(“null”,”nuller”);
System.out.println(conMap);
}
}

 

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
{null=null-1, null1=nuller}
{null=nuller, null1=null}

If we put null as key in treemap or hashtable or concurrentHastable then it won’t  throws any  error at Compile Time.but it will throw below error at runtime

D:\OCJP\imports>javac StaticVsNormalVsNo_Imports.java

D:\OCJP\imports>java StaticVsNormalVsNo_Imports
2147483647
-2147483648
7b
true
[10]
{null=nuller, null1=null, null2=null}
{null=nuller, null3=null, null1=null, null2=null}
Exception in thread “main” java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:464)
at StaticVsNormalVsNo_Imports.main(StaticVsNormalVsNo_Imports.java:44)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s