[英]add elements in arraylist inside hashmap
我正在尝试动态构建 String 和 arraylist 类型的动态哈希图。 我有一些来自服务器的 json 数据,而不是声明许多数组列表,我想将它们保存在哈希图中,字符串作为键,数组列表作为值。
这是我现在正在做的
ArrayList<classproperty> allStu;
ArrayList<classproperty> allEmp;
HashMap<String, ArrayList<classproperty>> hash;
if (type.equals("Student")) {
prop = new classproperty("Student", info.getJSONObject(i).getJSONObject("student").getJSONArray("class").getJSONObject(s).getJSONObject("type").getString("name"));
allStu.add(prop);
}
if (type.equals("Emp")) {
prop = new esSignalProperty("Emp", info.getJSONObject(m).getJSONObject("emp").getJSONObject(s).getJSONObject("dept").getString("name"));
allemp.add(prop);
}
hash.put("Student", allStu);
hash.put("Emp", allemp);
所以这是一种丑陋的方法......我想通过直接放入hashmap而不声明这么多arraylist来做到这一点。 请忽略 json 字符串提取,因为它只是虚拟的。
您只需要在开始时初始化数组列表,然后根据键添加值即可。 如果你知道我猜你知道你可以这样做的关键
public HashMap<String, ArrayList<classproperty>> hash
hash.put("Student", new ArrayList<classproperty>());
hash.put("Emp", new ArrayList<classproperty>());
就像@steffen 提到的一样,但有细微的变化
hash.get("Student").add(prop);
hash.get("Emp").add(prop);
这与其他目的没有什么不同,但可能仍然可以提供帮助。
hash.get("Student").put(prop)
可能是一个解决方案,因为你知道地图内的钥匙。
使用这种方式,您可以省去 'allStu' 和 'allEmp' 列表,因为您可以直接从地图中获取它们。
我建议使用已经支持此功能的 Guava 库中的MultiMap
。 如果您不打算导入这个库,那么您可以手动滚动自己的库作为Map<K, List<V>>
的包装器:
//basic skeleton of the multimap
//as a wrapper of a map
//you can define more methods as you want/need
public class MyMultiMap<K,V> {
Map<K, List<V>> map;
public MyMultiMap() {
map = new HashMap<K, List<V>>();
}
//in case client needs to use another kind of Map for implementation
//e.g. ConcurrentHashMap
public MyMultiMap(Map<K, List<V>> map) {
this.map = map;
}
public void put(K key, V value) {
List<V> values = map.get(key);
if (values == null) {
//ensure that there will always be a List
//for any key/value to be inserted
values = new ArrayList<V>();
map.put(key, values);
}
values.add(value);
}
public List<V> get(K key) {
return map.get(key);
}
@Override
public String toString() {
//naive toString implementation
return map.toString();
}
}
然后只需使用您的多图:
MyMultiMap myMultiMap = new MyMultiMap<String, ClassProperty>();
myMultiMap.put("student", new ClassProperty(...));
myMultiMap.put("student", new ClassProperty(...));
System.out.println(myMultiMap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.