如何为特定对象创建哈希映射 [英] How to create a hashmap for a specific object
本文介绍了如何为特定对象创建哈希映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编辑:
@Oscar Lopez
@Oscar Lopez
我已经添加了您指定的代码,现在有以下代码:
import java.util。 HashMap的;
import java.util.Map;
I have added the code you specified, and now have the following: import java.util.HashMap; import java.util.Map;
public class Character{
public String name;
private HashMap<String, String> stats;
public Character(String charName){
name = charName;
stats.put("Strength", "5");
stats.put("Dexterity", "5");
stats.put("Constitution", "5");
stats.put("Intelligence", "5");
stats.put("Strength", "5");
stats.put("Wisdom", "5");
}
public String getStat(String name) {
return stats.get(name);
}
public static void main(String[] arguments){
Character tanis = new Character("Tanis");
System.out.println(tanis.getStat("Dexterity"));
}
}
它似乎正确编译,但它不会不喜欢我试图把 stats.put
的东西加入到hashmap中,我该如何去做这件事?
And it seems to be compiling correctly, but it doesn't like the way I am trying to stats.put
things into the hashmap, how should I go about doing this?
import java.util.HashMap;
public class Character{
public String name;
private static HashMap<String, String> stats;
public Character(String charName){
name = charName;
stats = new HashMap<String, String>();
stats.put("Strength", "5");
stats.put("Dexterity", "5");
stats.put("Constitution", "5");
stats.put("Intelligence", "5");
stats.put("Strength", "5");
stats.put("Wisdom", "5");
}
public String getStat(String statName) {
return stats.get(statName);
}
public static void changeStat(Character character, String statName, String newStatValue) {
character.stats.put(statName, newStatValue);
}
public static void main(String[] arguments){
Character tanis = new Character("Tanis");
System.out.println(tanis.getStat("Dexterity"));
Character xander = new Character("Xander");
changeStat(xander, "Dexterity", "7");
System.out.println(xander.getStat("Dexterity"));
System.out.println(tanis.getStat("Dexterity"));
}
}
//Prints out
//5
//7
//7
为什么tanis.getStat变为7?
Why is tanis.getStat changing to 7?
推荐答案
在 Character
类中声明 HashMap
作为一个属性,那么你可以像你一样访问它打算:
Declare the HashMap
as an attribute in the Character
class, then you can access it like you intend:
public class Character {
private HashMap<String, String> stats;
public String getStat(String name) {
return stats.get(name);
}
}
// elsewhere
Character tanis = new Character("Tanis");
System.out.println(tanis.getStat("Dexterity"));
这篇关于如何为特定对象创建哈希映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文