根据键名从 HashMap 获取字符串值 [英] get string value from HashMap depending on key name
问题描述
我有一个带有各种键和值的 HashMap
,我怎样才能得到一个值?
I have a HashMap
with various keys and values, how can I get one value out?
我在地图中有一个名为 my_code
的键,它应该包含一个字符串,我怎样才能在不必遍历地图的情况下获得它?
I have a key in the map called my_code
, it should contain a string, how can I just get that without having to iterate through the map?
到目前为止我有..
HashMap newMap = new HashMap(paramMap);
String s = newMap.get("my_code").toString();
我期待看到一个 String
,例如ABC"或DEF",因为这是我最初放入的内容,但如果我执行 System.out.println()
我得到类似 java.lang.string#F0454
I'm expecting to see a String
, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println()
I get something like java.lang.string#F0454
抱歉,我对地图不太熟悉,你可能猜到了;)
Sorry, I'm not too familiar with maps as you can probably guess ;)
推荐答案
只需使用 Map#get(key)
?
Just use Map#get(key)
?
Object value = map.get(myCode);
这里有一个关于地图的教程,你可能会发现它很有用:http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html.
Here's a tutorial about maps, you may find it useful: http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html.
您使用以下内容编辑了您的问题:
you edited your question with the following:
我期待看到一个字符串,例如ABC"或DEF",因为这是我最初放入的内容,但是如果我执行 System.out.println() 我得到类似java.lang.string#F0454
抱歉,我对地图不太熟悉,你可能猜到了;)
您正在看到 Object#toString()
.但是 java.lang.String
应该已经实现了,除非您创建了一个 custom 实现,名称中带有小写的 s
:java.lang.string
.如果它实际上是一个自定义对象,那么无论何时执行 System.out.println()
都需要重写 Object#toString()
以获得人类可读的字符串"> 或 toString()
在所需的对象上.例如:
You're seeing the outcome of Object#toString()
. But the java.lang.String
should already have one implemented, unless you created a custom implementation with a lowercase s
in the name: java.lang.string
. If it is actually a custom object, then you need to override Object#toString()
to get a "human readable string" whenever you do a System.out.println()
or toString()
on the desired object. For example:
@Override
public String toString() {
return "This is Object X with a property value " + value;
}
这篇关于根据键名从 HashMap 获取字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!