简体   繁体   English

java - 用相同的键+不同的值替换hashmap中的键+值

[英]java - replace key + values in hashmap with identical key + different values

I have researched this question for ages and cannot get it right! 我已经研究了这个问题多年了,不能正确!

I have a populated hashmap and an identically formatted hashmap ( Map<Integer, ArrayList<String>> ) that I have been working on (it has key value/s equal to other keys in the populated hashmap such as 0,1,2 etc). 我有一个填充的hashmap和一个相同格式的hashmap( Map<Integer, ArrayList<String>> ),我一直在处理它(它的键值/ s等于填充的hashmap中的其他键,如0,1,2等)。 When I use the .put command to update the populated hashmap the few/one I have been working on replaces everything in the populated hashmap - is this normal? 当我使用.put命令更新填充的hashmap时,我一直在努力的几个/一个替换填充的hashmap中的所有内容 - 这是正常的吗? Where am I going wrong? 我哪里错了? I was expecting it to simply replace the key in question + values.... 我期待它只是替换有问题的键+值....

Excuse the not supplying code but it would mean posting quite an amount to demonstrate, just wondering if anyone could help explain where this might be going wrong. 请原谅不提供代码,但这意味着要发布相当数量的证明,只是想知道是否有人可以帮助解释这可能出错的地方。 I could throw something together to show if needed... 如果需要,我可以把东西放在一起展示......

Much obliged! 多谢!

This is how a code example might look like: 这是代码示例的样子:

import java.util.*;

public class NumFormEx
{
    public static ArrayList <String> listIt (String... params) 
    {
        ArrayList <String> as = new ArrayList <String> ();
        for (String s: params)
            as.add (s);
        return as;
    }

    public static void main (String args[])
    {
        Map <Integer, ArrayList<String>> mils = new HashMap<Integer, ArrayList<String>> ();
        mils.put (1, listIt ("foo", "bar")); 
        mils.put (2, listIt ("zacka", "zacka")); 
        System.out.println ("mils:\t" + mils);
        mils.put (1, listIt ("foobar"));        
        System.out.println ("mils:\t" + mils);
    }
}

Testing: 测试:

java NumFormEx
mils:   {1=[foo, bar], 2=[zacka, zacka]}
mils:   {1=[foobar], 2=[zacka, zacka]}

I would say: as expected. 我会说:正如所料。

Since map doesn't allow duplicate values you can do : 由于map不允许重复值,您可以执行以下操作:

myMap.put(2, new ArrayList<String>());

This will take element with key 2 and replace it's list with new ("blank") list. 这将使用键2的元素,并用新的(“空白”)列表替换它的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM