Java HashMap Class Declaration

‮w//:sptth‬ww.lautturi.com
Java HashMap Class Declaration

To declare a HashMap in Java, you can use the HashMap class of the java.util package.

Here is an example of how to declare a HashMap object that maps strings to integers:

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();

In this example, the map variable is a HashMap object that maps strings to integers. The HashMap class is a generic class, which means that you need to specify the types of the keys and values that the map will hold. In this case, the keys are strings and the values are integers.

You can also specify the initial capacity and load factor of the HashMap when you create it.

For example:

HashMap<String, Integer> map = new HashMap<>(16, 0.75f);

The initial capacity is the number of buckets in the hash table, and the load factor is the maximum ratio of elements to buckets. The HashMap class will automatically resize the hash table when the number of elements exceeds the capacity times the load factor.

Once you have created a HashMap, you can add elements to it using the put method, retrieve elements from it using the get method, and remove elements from it using the remove method.

For example:

map.put("apple", 1);
int value = map.get("apple");
map.remove("apple");

The HashMap class also provides various other methods for working with the map, such as containsKey, containsValue, and keySet. You can refer to the Java documentation for more information on these methods.

Created Time:2017-11-03 22:21:03  Author:lautturi