gpt4 book ai didi

java - HashMap,根据 Key 为 ArrayList 添加新值

转载 作者:行者123 更新时间:2023-11-29 07:11:57 24 4
gpt4 key购买 nike

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

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}

我需要能够对此进行添加和删除值。

我对 Java 集合还很陌生(很明显)。如果它们只有 1 对 1 的关系,并且 hashmap 是 1:1,我就能让事情正常进行。所以一个非常简单的 addingMethod 是这样的:

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

将得到一个字符串 string hashmap,但是当然如果我用一个新的键值对重用一个键,原始键值就会被踩到并消失。但是,当谈到动态地使用散列映射和数组列表时,并且超出 1:1 键:值关系时,我迷路了。

最佳答案

听起来你需要一个 MultiMap , 由 Google 的大神 Guava libraries 提供:

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

关于java - HashMap<String, ArrayList>,根据 Key 为 ArrayList 添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com