
Finally, this class is not synchronized and thus, if an application uses multiple threads, the map must be synchronized externally.Ī simple example that uses a TreeMap is shown below: Also, this class maintains order on its elements. The TreeMap is a Red-Black tree implementation that is sorted according to the natural ordering of its keys, or by a Comparator provided at the creation time. The next statements throw a NullPointerException, if uncommented.Īfter clear operation, size: 0 2.3 TreeMap This class contains two fundamental parameters: initial capacity and performance, with the same definitions as the HashMap class.Ī simple example that uses a HashTable is shown below: However, neither the key nor the value can be null.

The HashTable class implements a hash table and maps keys to values. ("After clear operation, size: " + vehicles.size()) Ī sample execution is shown below: Total vehicles: 4Īfter clear operation, size: 0 2.2 HashTable ("Found total " + vehicles.get(searchKey) + " " + searchKey + " cars!\n") Iterate over all vehicles, using the keySet method. The capacity is defined as the number of buckets in the hash table, while the load factor is a measure that indicates the maximum value the hash table can reach, before being automatically increased.Ī simple example that uses a HashMap is shown below: Finally, a HashMap contains two fundamental parameters: initial capacity and performance. Also, this class does not maintain any order among its elements and especially, it does not guarantee that the order will remain constant over time. A HashMap is a hash table-based implementation of the Map interface. The most common class that implements the Map interface is the Java HashMap. In this chapter, we will present the most common and used. There are many classes that implement the Java Map interface. size: Returns the number of key-value pairs currently in the map.remove: Removes the requested key and its value from the map, if the key exists.put: Adds the requested key-value pair in the map.keySet: Returns a Set that contains all keys of the map.entrySet: Returns a Set view of the mappings contained in this map.

get: Retrieve the value of the requested key.equals: Compares an Object with the map for equality.containsValue: Returns true if the map contains the requested value.containsKey: Returns true if the map contains the requested key.clear: Removes all the elements from the map.
