How do you create a dictionary in Java?
To create a dictionary (or map) in Java, you can use the Map
interface and its implementing classes.
The Map
interface is a part of the java.util
package and represents a key-value mapping. It has methods for inserting, deleting, and looking up values based on their keys.
There are several implementing classes of the Map
interface, including HashMap, TreeMap
, and LinkedHashMap
. Each of these classes has its own characteristics and trade-offs, and you can choose the one that best fits your needs.
Here is an example of how to create a dictionary (HashMap) in Java:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> dictionary = new HashMap<>();
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
}
}
This code creates a HashMap with String
keys and Integer
values and adds three key-value pairs to it.
You can use the put()
method to add key-value pairs to the map, the get()
method to look up a value based on its key, and the remove()
method to delete a key-value pair.
For example:
int value = dictionary.get("apple"); // Returns 1
dictionary.remove("apple"); // Removes the "apple" key-value pair
You can also use the containsKey()
method to check if a key is present in the map and the size()
method to get the number of key-value pairs in the map.
boolean hasApple = dictionary.containsKey("apple"); // Returns false
int size = dictionary.size(); // Returns 2
It is important to note that the Map
interface and its implementing classes do not allow duplicate keys. If you try to insert a key-value pair with a key that is already present in the map, the value will be overwritten.