是否可以在 Java 中返回 HashMap 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37971533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:59:30  来源:igfitidea点击:

Is it possible to return a HashMap object in Java?

javahashmap

提问by user6437583

I have a method that maps keywords to a certain value. I want to return the actual hashmap so I can reference its key/value pairs

我有一种方法可以将关键字映射到某个值。我想返回实际的哈希图,以便我可以引用它的键/值对

回答by Cache Staheli

Yes. It is easily possible, just like returning any other object:

是的。这很容易实现,就像返回任何其他对象一样:

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;
}

Elsewhere,

别处,

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.

Note, you should prefer to make the return type Mapinstead of HashMap, as I did above, because it's considered a best practice to always program to an interface rather than a concrete class. Who's to say that in the future you aren't going to want a TreeMapor something else entirely?

请注意,您应该更喜欢使用 return typeMap而不是HashMap,就像我上面所做的那样,因为始终将程序编程为 interface 而不是具体的 class被认为是最佳实践。谁能说将来你不会TreeMap完全想要一个或其他东西?