如何在单个列表中添加多个值HashMap <integer,arraylist <user =“”>&gt; map1 = new HashMap <integer,arraylist <user =“”>&gt;();

时间:2015-06-27 07:05:27

标签: java

 HashMap<Integer, ArrayList<User>> map1 = new HashMap<Integer, ArrayList<User>>(); 

现在假设Integer为101,我的数组列表值为[jan,10,200,city]。所以,如果我显示我的列表,它将像

101 :[jan,10,200,city]. 

如果我添加另一个就像

101 :[jan,10,200,city].
102:[prav,103,2023,city]. 

但是要在运行时添加这些东西

2 个答案:

答案 0 :(得分:1)

查看放置功能:Oracle Documentation - HashMap - Put

例如,让我们说你有一个

ArrayList<User> aList = new ArrayList<User>();

您将此列表设置为您想要的任何内容,然后执行

map1.put(101, aList);

注意:我认为你的意思是创建一个

HashMap<Integer, User>();

因为您的整数键仅指向一个具有多个属性(日期,城市等)的用户。在这种情况下,put的第二个参数将是User而不是ArrayList。

希望这会有所帮助。 (抱歉格式错误,这是我的第一个回答)

答案 1 :(得分:0)

代码如下,将userList添加到Map

   package com.orm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

class User {
User(String name, int id, String city) {
    this.name = name;
    this.id = id;
    this.city = city;
}

String name;
int id;
String city;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

}

  public class Main {

public static void main(String[] args) {
     Map<Integer ,ArrayList<User> > userMap = new HashMap<Integer, ArrayList<User>>();
     User user1 = new User("Jan", 101, "city");
     User user2 = new User("Prav", 103, "city");
     ArrayList<User>userList = new ArrayList<User>();
     userList.add(user1);
     userList.add(user2);
     userMap.put(1,userList )
        }

}