安卓 - 用不同的数据类型填充哈希图



是否可以像这样填充哈希图?

final HashMap<String, String> map = new HashMap<>();
map.put("path", path);
map.put("tableName", "table");
map.put("fileType", fileType);
final HashMap<String, String> option = new HashMap<>();
map.put("option", option.put("header", "true"));

还是有比这更正确(或更好(的方法? 因为当我尝试打印"地图"时,键"选项"没有价值。

提前致谢

你不能这样做,你必须正确指定数据类型,

final HashMap<String, String> map = new HashMap<>();
map.put("path", path); //path has to be a variable pointing to a string
map.put("tableName", "table");
map.put("fileType", fileType); // filetype has to be a variable pointing to a string
final HashMap<String, String> option = new HashMap<>(); 
map.put("option", option.put("header", "true")); //this is wrong
HashMap<String,Map<String,String>> option = new HashMap<String,HashMap<String,String>>();
option.put("Key",map);

示例:创建和填充地图

Map<String, Map<String, Value>> outerMap = new HashMap<String, HashMap<String, Value>>();
Map<String, Value> innerMap = new HashMap<String, Value>();    
innerMap.put("innerKey", new Value());

存储地图

outerMap.put("key", innerMap);

检索地图及其值

Map<String, Value> map = outerMap.get("key");
Value value = map.get("innerKey"); 

您可以通过以下方式存储数据:

public static void main(String[] args){
Map<String, String> dataMap = new HashMap<>();
dataMap.put("key1", "Hello");
dataMap.put("key2", "Hello2");
Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", dataMap);
map.put("3", "Value3");
Object obj = map.get("1");
printData(obj);
Object obj2 = map.get("2");
printData(obj2);
Object obj3 = map.get("3");
printData(obj3);
}
private static void printData(Object obj) {
if (obj instanceof Integer) {
Integer integer =convertInstanceOfObject(obj, Integer.class);
System.out.println(integer);
}else if( obj instanceof HashMap){
HashMap<String, String> resMap = convertInstanceOfObject(obj, HashMap.class);
System.out.println(resMap);
}else if( obj instanceof String ){
String data = convertInstanceOfObject(obj, String.class);
System.out.println(data);
}
}

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}

输出:

1
{key1=Hello, key2=Hello2}
Value3

map类型是Map<String, Object>,因为它的值可以是任何类型的对象

HashMap<String ,Object> data= new HashMap<>();
data.put("post",myPost);
data.put("username",userName);
data.put("date" ,date);

您可以在android studio-java中使用不同的数据类型与HashMap一起使用

最新更新