你如何在Java中创建一个字典?
我正在尝试实现一本字典(如实体书)。我有一个单词列表及其含义。
I am trying to implement a dictionary (as in the physical book). I have a list of words and their meanings.
Java提供哪些数据结构/类型,用于将单词列表及其含义存储为键/值对。
What data structure / type does Java provide to store a list of words and their meanings as key/value pairs.
如果给出一个键,我可以找到并返回值吗?
How, given a key, can I find and return the value?
您将需要一个 Map< String,String>
。实施 地图
的类界面包括(但不限于):
You'll want a Map<String, String>
. Classes that implement the Map
interface include (but are not limited to):
HashMap
LinkedHashMap
Hashtable
每个都是针对某些情况设计/优化的(请访问他们各自的文档以获取更多信息)。 HashMap
可能是最常见的;
Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap
is probably the most common; the go-to default.
例如(使用 HashMap
):
Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal