[英]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? 为什么我不能拥有一个Objects数组,每个对象都是一个hashmap?
You have to cast the Object
to a Map
. 您必须将Object
投射到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. Object
没有put
方法。
You can definitely have an array of Objects where each object is a HashMap. 您绝对可以拥有一个Objects数组,其中每个对象都是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). 第二个代码段的唯一问题是,在运行时,编译器不知道IEXDivMap [i]的类型(不知道它指向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. 因此,在那个时候,它只会向用户公开在Object类本身上定义的那些方法,而不是在HashMap类中定义的那些方法。
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 如果将IEXDivMap [i]转换为类似于-> ((HashMap)IEXDivMap[i])
的HashMap,则如果IEXDivMap [i]引用的对象实际上是HashMap,则编译器将调用HashMap类中定义的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.