将数组添加到HashMap中

时间:2016-06-01 09:17:21

标签: java arrays hashmap

我正在尝试向HashMap添加一个数组,但是我找不到一个好的解决方案。 现在我有:

Person[] array;

public void add(Person p){

    HashMap<String, ArrayList<String>> people = 
    new HashMap <String, ArrayList<String>>();

    people.put("key", p);

但是,put方法不接受“p”。 我知道我也可以使用循环来做到这一点,但我不知道如何。我在考虑像:

HashMap<String, ArrayList<String>> people = 
new HashMap <String, ArrayList<String>>();

map.put("key", new ArrayList<String>>());

for (int i=0;i<Person.size(); i++) {
    map.get("sth").add(Person[i]); 
}

将数组元素添加到哈希映射中的另一种方法是什么?或者我应该改变两个中的任何一个?在此先感谢,我刚开始使用Java,所以非常感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

HashMap<String, ArrayList<String>>  

查看它要求list of strings的通用类型,并且您尝试添加person,这将导致错误。

您可以将generic上的hashmap更改为此

HashMap<String,Person> persons = new  HashMap<String,Person>();

然后您可以使用map方法

将人员添加到put
persons.put("key",person);

如果您需要向array of persons添加map,可以使用以下方法进行操作。

public void foo(Person[] array){
        HashMap<String , Person[]> persons = new HashMap<String , Person[]>();
        persons.put("key", array);
    }

答案 1 :(得分:0)

数组是与ArrayList不同的对象。我建议你一直使用ListArrayList。在大多数情况下,您不需要普通数组。

答案 2 :(得分:0)

您需要先创建Person的List或ArrayList,然后才能添加它。

public void add(Person p){
ArrayList<Person> p1 = new ArrayList<>();

    HashMap<String, ArrayList<String>> people = new HashMap <>();

    people.put("key", p1.add(p));
相关问题