To instantiate a HashMap
object in Java, you can use the following syntax:
HashMap<KeyType, ValueType> map = new HashMap<>();
Here, KeyType
is the type of the keys in the map and ValueType
is the type of the values in the map. You can specify any type for the keys and values as long as they are compatible with the HashMap
class.
For example, to create a HashMap
that maps strings to integers, you can use the following code:
HashMap<String, Integer> map = new HashMap<>();
You can also specify the initial capacity and load factor of the HashMap
when instantiating it. For example:
HashMap<String, Integer> map = new HashMap<>(16, 0.75f);
Here, the initial capacity is set to 16 and the load factor is set to 0.75.
You can then add key-value pairs to the map using the put
method:
map.put("key1", 1); map.put("key2", 2); map.put("key3", 3);
You can retrieve the value for a given key using the get
method:
int value = map.get("key1");
You can also use the containsKey
method to check if a key is present in the map:
if (map.containsKey("key1")) { // Key is present in the map } else { // Key is not present in the map }