Example to show Hash map exception in java

The implementation of map interface is based on Hash table.
Interface in Mapping -
1)The Hash Map implements map.
2)The Tree Map implements sorted map.
3)Map-Entry describe the access method to key-value
pairs
Understand with Example
Hash map in java is same as the Hash table. The
program given below gives the brief description of exception that occurs while
executing Hash map.
Hash Map hash Map = new Hash Map():-This
is the way for creating a HashMap.Here we have created an empty Hash Map.
hashMap.put("ABS", new Double(3434.34)):-This is the
method of the Hash Map for adding the specified value with the specified key in this
map.
hashMap.entrySet():-This method returns a collection view of the mappings contained in this map.
me.getKey( ):- This method return you the
key-value pair stored in a Map.
On execution of the code, the code show you an
exception indicating an string cannot be converted into double.
Hashmapexception.java
import java.util.*;
import java.util.Iterator;
public class Hashmapexception {
public static void main(String[] args) {
HashMap hashMap = new HashMap();
hashMap.put("ABS", new Double(3434.34));
hashMap.put("ABD", new Double(123.22));
hashMap.put("cccc", "jdshgjhs");
Set set = hashMap.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
double balance = ((Double) hashMap.get("cccc")).doubleValue();
hashMap.put("cccc", new Double(balance + 1000));
System.out.println("balance : " + hashMap.get("cccc"));
}
}
|
|
Output of the program
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at Hashmapexception.main(Hashmapexception.java:20)
Java Result: 1 |
Download source code

|