本文介绍了HashMap<String, ArrayList>,根据 Key 将新值附加到 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个测试驱动的开发问题(我需要根据提供的 junit 方法使其工作)基于实现一个使用字符串作为键和 ArrayLists 作为值的 HashMap.密钥需要能够支持一个或多个对应的值.我需要以一种可以从散列中添加或减去值的方式来设置我的方法,然后查看散列的更新内容.我的努力是从下面显示的单元方法中获取信息(执行 myClass 和它的 addMethod 方法)并将其正确放入哈希中.

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 的关系,并且哈希图是 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);

将得到一个字符串字符串哈希映射,但是当然,如​​果我用新的键值对重用键,原始键值会被踩到并消失.但是,当涉及到动态处理哈希图和数组列表时,超出 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,由 Google 伟大的 番石榴库:

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

类似于 Map 的集合,但可以将多个值与单个键关联.如果使用相同的键但不同的值调用 put(K, V) 两次,则多重映射包含从键到两个值的映射.

这篇关于HashMap<String, ArrayList>,根据 Key 将新值附加到 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 08:36