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

前端 未结 5 1829
别那么骄傲
别那么骄傲 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:48

    The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

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

    For the above code to work, the Object must be cast to an ArrayList:

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

    However, probably the better way would be to use generic collection objects in the first place:

    HashMap> dictMap =
        new HashMap>();
    
    // Populate the HashMap.
    
    ArrayList current = new ArrayList();      
    if(dictMap.containsKey(dictCode)) {
        current = dictMap.get(dictCode);   
    }
    
    
    

    The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

    For more information on generics, The Java Tutorials has a lesson on generics.

    提交回复
    热议问题