簡體   English   中英

在 hashmap 內的 arraylist 中添加元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM