簡體   English   中英

如何在單個列表中添加多個值HashMap <Integer, ArrayList<User> &gt; map1 =新的HashMap <Integer, ArrayList<User> &gt;();

[英]How to add a multiple value in a single list HashMap<Integer, ArrayList<User>> map1 = new HashMap<Integer, ArrayList<User>>();

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

但是這些東西要在運行時添加

查看put函數: Oracle文檔-HashMap-Put

舉例來說,假設您有一個

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

您可以將此列表設置為所需的任何內容,然后執行

map1.put(101, aList);

注意:我認為您的意思是創建一個

HashMap<Integer, User>();

因為您的整數鍵僅指向一個具有多個屬性(日期,城市等)的用戶。 在這種情況下,put的第二個參數將是User而不是ArrayList。

希望這可以幫助。 (對不起,格式不好,這是我的第一個答案)

代碼如下將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 )
        }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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