HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?
How is the HashMap declaration expressed in that scope? It should be:
HashMap<String, ArrayList> dictMap
If not, it is assumed to be Objects.
For instance, if your code is:
HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);
that will not work. Instead you want:
HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);
The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.
Also note that ArrayList
is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList
contains your class MyClass
, the line above might be:
HashMap<String, ArrayList<MyClass>> dictMap
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
Works fine... maybe you find your mistake in my code.
I suppose your dictMap is of type HashMap
, which makes it default to HashMap<Object, Object>
. If you want it to be more specific, declare it as HashMap<String, ArrayList>
, or even better, as HashMap<String, ArrayList<T>>