Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot define and instantiate a HashMap?

Why this code line:

Map<String, Integer> phoneDirectory = new HashMap<String, Integer>();  

Keeps giving me a compilation error [Type HashMap does not take a parameter].
Replacing type parameters <String, Integer> with an empty set <> also gives me the following error:

cannot infer type arguments for HashMap reason: cannot use <> with non-generic class HashMap.    

I tried to remove the parameter set, but then I need to cast the HashMap into a Map type object which results in the following class cast exception:

[Exception in thread "main" java.lang.ClassCastException: javaApp.HashMap cannot be cast to java.util.Map at javaApp.HashMap.main]

I'm using JDK1.8 API. Any Help please.

Update 1
Using import java.util.HashMap results in the follwoing compilation error:

HashMap is already Defined in this compilation unit.

1 Answers

You are using: javaApp.HashMap

you should be using java.util.HashMap

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Make sure you import the right hashmap. If you are using your own HashMap class for academic purposes, as you should really using the standard library one. Then make sure it implements Map: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

like image 159
Simba Avatar answered Dec 11 '25 21:12

Simba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!