我正在尝试向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,所以非常感谢任何帮助!
答案 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
不同的对象。我建议你一直使用List
或ArrayList
。在大多数情况下,您不需要普通数组。
答案 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));