[英]java: Store HashMap<String, String> in ArrayList<Object>
ArrayList<Object> parameters = new ArrayList<Object>();
HashMap<String, String> parameter = new HashMap<String, String>();
parameter.put("key", "value");
parameters.add(parameter);
parameters.add((String) "additionalData"); //this line is here for a reason
destinationFunction(parameters);
....
destinationFunction(ArrayList<Object> data){
HashMap<String, String> imported = (HashMap<String, String>) data.get(0);
String value = imported.get("key");
}
How do i achieve this? 我该如何实现? When i try i receive no errors up until like 2 of destinationFunction where i receive null pointer exception
当我尝试时,直到destinationFunction的2一样,我都没有收到错误,我收到了空指针异常
ArrayList<Object> parameters = new ArrayList<Object>();
relpace this line with what you want to store in array list like you want to store hash map then create arraylist of type hash map 用要存储在数组列表中的内容来重复此行,就像要存储哈希图一样,然后创建哈希表类型的arraylist
ArrayList<HashMap<String, String>> parameters = new ArrayList<HashMap<String, String>>();
hope this will help you 希望这个能对您有所帮助
使用哈希图的数组列表
ArrayList<HashMap<String, String>>()
Try to put ArrayList<HashMap<String, String>>
instead of ArrayList<Object>
尝试放置
ArrayList<HashMap<String, String>>
而不是ArrayList<Object>
create a HashMap and add into the ArrayList. 创建一个HashMap并添加到ArrayList中。 For Example:-
例如:-
ArrayList<HashMap<String, String>> list = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("KEY", "VALUE");
list.add(map); //Add the map into list
You did not specified what type are you storing in your arrayList. 您未指定要在arrayList中存储什么类型。 But you assume in your
destinationFunction
that this list contains only HashMap<String, String>
elements. 但是您假设在
destinationFunction
,此列表仅包含HashMap<String, String>
元素。 Besides terrible code style it is okay in java to write so. 除了可怕的代码风格外,在Java中也可以这样编写。 But you made a mistake when put in your arrayList an element of type
String
which is breaking your assumptions in destinationFunction
. 但是,当将arrayType元素放入
String
类型的元素却破坏了destinationFunction
的假设时,您犯了一个错误。
PS Try to write more type safe code and avoid generic types with Object
type parameter. PS尝试编写更多类型安全的代码,并避免使用带有
Object
类型参数的泛型类型。
Alternative Solution would be using JsonObject
and JsonArrays
. 替代解决方案将使用
JsonObject
和JsonArrays
。 they are perfect for such "scenarios" (working with String,Integer and etc with combination of List and Map). 它们非常适合此类“方案”(与List,Map结合使用String,Integer等)。
they may also be useful for complex object(eg working with Images) but will be abit more difficult to implement. 它们对于复杂的对象(例如,使用图像)可能也很有用,但实施起来会更加困难。 in such cases please refer to java_serialization
在这种情况下,请参考java_serialization
in your case use JSONArray
instead of your ArrayList
and JsonObject
instead of HashMap
. 在您的情况下,请使用
JSONArray
而不是ArrayList
和JsonObject
而不是HashMap
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.