【发布时间】:2018-05-19 22:14:03
【问题描述】:
我去向哈希表发送一个字符串,并让它检查它的键(它们是 ArrayList)。如果 ArrayList 包含给定的字符串,则返回键的值。
package com;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
public class TestMain {
private static final String str1 = "n";
private static final String str2 = "north";
private static final Hashtable<ArrayList<String>,String> compassDirection = new Hashtable<ArrayList<String>,String>() {{
put(new ArrayList<>(Arrays.asList("n", "north")), "North");
put(new ArrayList<>(Arrays.asList("s", "south")), "South");
put(new ArrayList<>(Arrays.asList("e", "east")), "East");
put(new ArrayList<>(Arrays.asList("w", "west")), "West");
}};
public static void main(String[] args) {
// print str1 as "North" from hashtable call
// print str2 as "North" from hashtable call
}
}
【问题讨论】:
-
为什么键是一个列表?您不能调用
get("n")或get("north")来查找"North"值。如果这是您想要的,您需要添加两个条目:put("n", "North")和put("north", "North") -
不要使用列表作为键。只需使用
HashMap<String,String>并将每个值放入与它对应的键一样多的次数。 -
@Andreas 我想我会这样做作为一种解决方法。但在未来,很高兴知道我是否可以使用 ArrayList 和 Contains 作为键...尤其是在我处理大型数组时。
-
这不是一种解决方法。它只是正确而不是错误地使用哈希表。哈希表需要知道您要查找的密钥的哈希值才能找到它。这就是哈希表工作的整个机制。如果您将列表存储为键,则需要再次提供该列表以进行查找,因为没有它,您将不知道正确的哈希值。
-
@FiddleFreak 不,你不能那样做。这不是地图的工作方式。
标签: java string arraylist hashtable