How do you create a dictionary in Java? [closed]

2019-01-08 03:17发布

I am trying to implement a dictionary (as in the physical book). I have a list of words and their meanings.

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?

4条回答
Animai°情兽
2楼-- · 2019-01-08 03:38

This creates dictionary of text (string):

Map<String, String> dictionary = new HashMap<String, String>();

you then use it as a:

dictionary.put("key", "value");
String value = dictionary.get("key");

Works but gives an error you need to keep the constructor class same as the declaration class. I know it inherits from the parent class but, unfortunately it gives an error on runtime.

Map<String, String> dictionary = new Map<String, String>();

This works properly.

查看更多
叛逆
3楼-- · 2019-01-08 03:51

Use Map interface and an implementation like HashMap

查看更多
叛逆
4楼-- · 2019-01-08 03:52

There's an Abstract Class Dictionary

http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html

However this requires implementation.

Java gives us a nice implementation called a Hashtable

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

查看更多
叼着烟拽天下
5楼-- · 2019-01-08 03:53

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

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.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal
查看更多
登录 后发表回答