简体   繁体   English

带有ArrayList的HashMap

[英]HashMap with ArrayList

I have a java question about a HashMap with an ArrayList in it. 我有一个关于带有ArrayList的HashMap的java问题。 The key is a string and the value is the ArrayList ( HashMap<String, ArrayList<Object>> ) 键是一个字符串,值是ArrayList( HashMap<String, ArrayList<Object>>

I am given a list of multiple keys and I need to put the corresponding values into the ArrayList, and I'm not sure how to do it. 我得到了一个多个键的列表,我需要将相应的值放入ArrayList,我不知道该怎么做。

Here's an example: 这是一个例子:

(What I am given) (我给的是什么)

ABC
ABC
ABC
123
123

The keys are actually file names so the file is the value for the ArrayList. 键实际上是文件名,因此该文件是ArrayList的值。 Now I have to separate those filenames so i can add the files to the ArrayList. 现在我必须分离这些文件名,以便我可以将文件添加到ArrayList。 Does this make sense? 这有意义吗?

This is the only code I have: 这是我唯一的代码:

Set<String> tempModels = Utils.getSettingSet("module_names", new HashSet<String>(), getActivity());
        for(String s : tempModels) {
            Log.d("Loading from shared preferences: ", s);
            String key = s.substring(0, 17);

        }

I believe you're looking for something like this, 我相信你正在寻找这样的东西,

List<Object> al = map.get(key);
if (al == null) {
  al = new ArrayList<Object>();
  map.put(key, al);
}
al.add(value);

Please note that the above uses raw Object Lists. 请注意,上面使用原始Object列表。 You should (if possible) pick a proper type, and use it. 您应该(如果可能)选择合适的类型,并使用它。

Edit 编辑

Some prefer the (slightly shorter) form, 有些人喜欢(略短)的形式,

if (!map.containsKey(key)) {
  map.put(key, new ArrayList<Object>());
}
map.get(key).add(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM