字符串数组转入HashMap集合对象
我有以下
String[] temp;
返回值
red
blue
green
我想将字符串数组添加到像 HashMap 这样的集合对象中,以便我可以检索任何类中的值,例如
HashMap hash = New HashMap();
hash.get("red");
hash.get("blue");
hash.get("green");
我怎样才能做到这一点?
谢谢
更新 1
String str = "red,blue,green";
String[] temp;
String delimiter = ",";
temp = str.split(delimiter);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
通过上面的代码,我想根据数组中的值检索值。例如,我想通过调用 hash.get("One") 从另一个类获取值,这将返回红色,hash.get("Two") 将返回蓝色等等。
I have the following
String[] temp;
which returns
red
blue
green
I would like to add the string array into a collection obejct like HashMap so that I could retrieve values in any class like
HashMap hash = New HashMap();
hash.get("red");
hash.get("blue");
hash.get("green");
How can I do this?
Thanks
Update 1
String str = "red,blue,green";
String[] temp;
String delimiter = ",";
temp = str.split(delimiter);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
With the above code, I would like to retrieve values based on values in array. E.g. I would like to get the values in from another class by calling hash.get("One"), which would return red, hash.get("Two") which would return blue and so forth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后你可以从地图中检索
hash.get(temp[i]);
Then you can retrieve from map
hash.get (temp[i]);
使用哈希映射并不能直接解决这个问题。目前你需要
这样
写,会产生一个字符串“blue”。
如果你有一个 hashMap,那么你可能会
这样
写,会产生“blue”。在任何一种情况下,您都将值转换为相应的字符串,但您确实需要知道“someNumber”。如果你想要“蓝色”,你需要知道要数字 1。
你可能需要的是使用命名良好的常量值:
你的客户现在可以编写诸如
[使用枚举比仅使用原始整数更好,但现在我们不要偏离数组和 hashMap]。
现在什么时候你可能更喜欢 hashMap 而不是数组?考虑您可能有更多颜色,例如 12695295 可能是“浅粉色”,16443110 可能是“淡紫色”。
现在,当您只使用其中的 500 个条目时,您确实不需要一个包含 16,443,110 个条目的数组。现在 HashMap 是一个非常有用的东西
等等。
Using a hash map won't solve this problem directly. Currently you need to write
so
yields a String "blue"
If you have a hashMap then instead you might write
so
Would yield "blue". In either case you are converting a value to a corresponding string, but you do need to know that "someNumber". If you want "blue" you need to know to ask for number 1.
It may be that what you need is to use nicely named constant values:
Your clients can now write code such as
[It is better to use enums than just raw ints, but let's not divert from arrays and hashMaps right now].
Now when might you prefer a hashMap instead of an array? Consider that you might have more colours, for example 12695295 might be "light pink" and 16443110 might be "lavender".
Now you really don't want an array with 16,443,110 entries when you are only using perhaps 500 of them. Now a HashMap is a really useful thing
and so on.