基于密钥字符串,ArrayList的>中追加新值的ArrayList,HashMap的&LT [英] HashMap<String, ArrayList>, Appending ArrayList with new values based on the Key

查看:155
本文介绍了基于密钥字符串,ArrayList的>中追加新值的ArrayList,HashMap的&LT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经被赋予了测试驱动开发的问题(我需要使它的基础上提供了JUnit方法的工作)的基础上实施,使用的密钥和用于的ArrayList值的字符串一个HashMap。关键需要能够支持一个或多个相应的值。我需要设置我的方法,我可以添加或哈希值中减去,然后看散列的更新内容的方法。我的斗争正在从单位方法提供的信息如下所示(MyClass的行使和它的addingMethod法)方法)并使其投入到正确的哈希值。

I've been given a test-driven development problem (I need to make it work based on the junit methods provided) based on implementing a HashMap that uses a strings for the keys and ArrayLists for the values. The key needs to be able to support one or more corresponding values. I need to set up my methods in a way that I can add or subtract values from the hash, and then see the updated contents of the hash. My struggle is taking info provided from the unit method shown below (exercising myClass and it's addingMethod method) methods) and getting it put properly into the hash.

void add() {
    myClass = new MyClass("key1", "value1");
    myClass.addingMethod("blargh", "blarghvalue");
    myClass.addingMethod("blargh2", "uglystring");
    myClass.addingMethod("blargh", "anotherstring");
    //and so on and so on............

有关我的最终结果,当我打印出来myClass的结果,我需要看是这样的:
    {blargh = [blarghvalue,anotherstring],blargh2 = uglystring}

For my end result, when I print out the results of myClass, I need to see something like: {blargh=[blarghvalue, anotherstring], blargh2=uglystring}

我需要能够添加到这一点,并删除值,以及

I need to be able to add to this, and remove values as well.

我很新的Java集合(明显)。我能得到的东西,如果他们只有一个1对1的关系工作,HashMap的是1:1。所以,一个很简单的addingMethod是这样的:

I'm very new to java collections (obviously). I can get things to work if they only have a 1 to 1 relationship, and the hashmap is 1:1. So a very simple addingMethod like this:

public void addingMethod(String key, String value) {
    hashMap.put(key, value);

会得到一个串串HashMap的,当然,如果我重复使用一个新的键值对的关键,原来的键值就会被踩了又走了。当谈到与包含HashMap和工作的ArrayList动态不过,和超过1:1键:价值关系,我迷路了。

Will get a string string hashmap, but of course if I reuse a key with a new key-value pair, the original key-value gets stepped on and goes away. When it comes to working with hashmaps and arraylists dynamically though, and beyond a 1:1 key:value relationship, I'm lost.

推荐答案

这听起来像你需要的 Multimap之 ,这是谷歌的巨大的 番石榴库

It sounds like you need a MultiMap, which is provided by Google's great Guava libraries:

类似于图的集合,但其可与一个单一的键的多个值相关联。如果调用把(K,V)的两倍,使用相同的密钥,但不同的价值观,multimap中包含的关键,这两个值的映射。

这篇关于基于密钥字符串,ArrayList的>中追加新值的ArrayList,HashMap的&LT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆