我有一种将关键字映射到某个值的方法。我想返回实际的hashmap,以便我可以参考其键/值对
是。就像返回其他任何对象一样,很容易成为可能:
public Map<String, String> mapTheThings(String keyWord, String certainValue)
{
Map<String, String> theThings = new HashMap<>();
//do things to get the Map built
theThings.put(keyWord, certainValue); //or something similar
return theThings;
}
其他地方,
Map<String, String> actualHashMap = mapTheThings("keyWord", "certainValue");
String value = actualHashMap.get("keyWord"); //The map has this entry in it that you 'put' into it inside of the other method.
注意,您应该更喜欢将返回类型的Map
而不是HashMap
进行,因为我上面做过,因为它被认为是始终编程到接口而不是具体类的最佳实践。谁会说,将来您不会完全想要TreeMap
或其他东西?