如何在声明时将项目添加到哈希表? [复制]
Posted
技术标签:
【中文标题】如何在声明时将项目添加到哈希表? [复制]【英文标题】:How to add item to Hashtable at Declaration? [duplicate] 【发布时间】:2020-12-28 09:47:15 【问题描述】:所以我正在尝试创建一个基于文本的冒险/地牢爬行游戏。我正在尝试使用与我在基于文本的 Pokemon 游戏中使用的系统类似的系统来存储物品、怪物等。这是我在 C# 中用于存储系统的功能代码。
public static Dictionary<string, pokemonTrainer> pokemonTrainers = new Dictionary<string, pokemonTrainer>()
"Robert", new pokemonTrainername="Robert",typesOfPokemon="Plant","Normal", levelMultiplier=0.4,
"James", new pokemonTrainername="James",typesOfPokemon="Plant","Normal","Water","Fire","Ice","Flying","Electric","Poison","Psychic","Fighting","Dark","Dragon","Fairy","Rock","Ghost","Ground","Bug",levelMultiplier=0.8
;
我想创建我的哈希表,其中包含某些键值对,就像在 C# 代码中所做的那样,而不是仅仅使用 .put() 添加它们,这可能吗?如果是这样,我会怎么做?如果不是,那么创建这样一个存储系统的最佳方法是什么?
如果它有帮助,这是我在 java 中对哈希表的声明,
public static Hashtable<Integer, monster> monster_data_base = new Hashtable<Integer, monster>()
;
这是我想成为键值对的值部分的怪物类。
class monster
private int health;
private int damage;
private String name;
private int level;
monster(int health, int damage, String name, int level)
this.health=health;
this.damage=damage;
this.name=name;
this.level=level;
String get_name()
return name;
int get_health()
return health;
int get_damage()
return damage;
void change_health(int change_in_durabilty)
health=health+change_in_durabilty;
int get_level()
return level;
【问题讨论】:
你检查过这个答案吗? ***.com/questions/6802483/… 【参考方案1】:创建一个静态方法来初始化您的静态哈希表对象。这将在加载类时初始化。
public class Main
public static Hashtable<Integer,String> mytable = new Hashtable<>();
static
initializeMytable();
// static initializer where you can initiate your static object
static void initializeMytable()
mytable.put(2,"sam");
public static void main(String[] args)
// use your table where you need it later
System.out.println(mytable);
【讨论】:
我查看了提供的链接,确实回答了我的问题,而且静态方法看起来也可以工作。所以我只是有疑问。 hashtable 和 hashmap 之间有什么区别,区别是否大到足以保证使用其中一个而不是另一个? HashMap 比 Hashtable 更常用。原因(来自 Oracle API 文档)-As of the Java 2 platform v1.2, Hashtable was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.
以上是关于如何在声明时将项目添加到哈希表? [复制]的主要内容,如果未能解决你的问题,请参考以下文章