HashMap with multiple values under the same key

前端 未结 22 2170
旧时难觅i
旧时难觅i 2020-11-22 06:49

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to

22条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 06:58

    You can do it implicitly.

    // Create the map. There is no restriction to the size that the array String can have
    HashMap map = new HashMap();
    
    //initialize a key chosing the array of String you want for your values
    map.put(1, new String[] { "name1", "name2" });
    
    //edit value of a key
    map.get(1)[0] = "othername";
    

    This is very simple and effective. If you want values of diferent classes instead, you can do the following:

    HashMap map = new HashMap();
    

提交回复
热议问题