简体   繁体   中英

How to insert hashmaps into an array of objects

Could someone explain why this works:

Map[] IEXDivMap = new Map[IEXJsonArray.length()];

    for (int i = 0; i < IEXJsonArray.length(); i++) {
        IEXDivMap[i] = new HashMap();
        JSONObject IEXJsonObject = IEXJsonArray.getJSONObject(i);

        IEXDivMap[i].put("exDate",IEXJsonObject.getString("exDate"));
        IEXDivMap[i].put("amount",IEXJsonObject.getString("amount"));            

    }

but this doesn't:

Object[] IEXDivMap = new Object[IEXJsonArray.length()];

    for (int i = 0; i < IEXJsonArray.length(); i++) {
        IEXDivMap[i] = new HashMap();
        JSONObject IEXJsonObject = IEXJsonArray.getJSONObject(i);

        IEXDivMap[i].put("exDate",IEXJsonObject.getString("exDate"));
        IEXDivMap[i].put("amount",IEXJsonObject.getString("amount"));            

    } 

Why can't I have an array of Objects each object being a hashmap?

You have to cast the Object to a Map .

Object[] IEXDivMap = new Object[IEXJsonArray.length()];

for (int i = 0; i < IEXJsonArray.length(); i++) {
    IEXDivMap[i] = new HashMap();
    JSONObject IEXJsonObject = IEXJsonArray.getJSONObject(i);

    IEXDivMap[i].put("exDate",IEXJsonObject.getString("exDate")); // this fails
    IEXDivMap[i].put("amount",IEXJsonObject.getString("amount"));

    ((Map) IEXDivMap[i]).put("exDate",IEXJsonObject.getString("exDate")); // this works
    ((HashMap) IEXDivMap[i]).put("exDate",IEXJsonObject.getString("exDate")); // this works           

} 

Object doesn't have a put method.

See also this question about casting.

You can definitely have an array of Objects where each object is a HashMap. The only problem with your second code snippet is that at runtime, the compiler doesn't know the type of IEXDivMap[i] (it doesn't know that it points to an object of type HashMap). So at that point of time, it will only expose to the user those methods which are defined on the Object class itself and not those defined in the HashMap class.

If you cast the IEXDivMap[i] to a HashMap like -> ((HashMap)IEXDivMap[i]) then the compiler invokes the methods defined in the HashMap class if the object referenced by IEXDivMap[i] is actually a HashMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM