HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

前端 未结 5 1880
别那么骄傲
别那么骄傲 2021-02-04 17:11

I\'m storing data in a HashMap with (key: String, value: ArrayList). The part I\'m having trouble with declares a new ArrayList \"current,\" searches the HashMap for the String

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 17:41

    How is the HashMap declaration expressed in that scope? It should be:

    HashMap dictMap
    

    If not, it is assumed to be Objects.

    For instance, if your code is:

    HashMap dictMap = new HashMap();
    ...
    ArrayList current = dictMap.get(dictCode);
    

    that will not work. Instead you want:

    HashMap dictMap = new HashMap();
    ...
    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> dictMap
    

提交回复
热议问题