"HashMap" is a "Map" interface implementation in Java that stores key-value pairs. It is part of Java's collections library and implements the data structure known as a hash table. The "HashMap" class belongs to the "java.util package".
Main features of "HashMap":Key-Value Pairs
Each element in a "HashMap" is a key-value pair, where the key is unique and maps to an associated value.
Efficiency in Data Recovery
The hash table implementation allows for efficient data retrieval. Given a key, "HashMap" can quickly find the corresponding value.
Unordered
Elements in a "HashMap" do not have a specific order. If you need a specific order, you can use "LinkedHashMap", which maintains the insertion order.
Allows Null Keys and Null Values
"HashMap" allows one key and multiple values to be null.Not Synced
The "HashMap" default implementation is not synchronized, which means it is not safe for concurrent use by default. If synchronization is required, you can use "Collections.synchronizedMap(Map<K, V> map)" to obtain a synchronized version.
Basic usage example:import java.util.HashMap;
import java.util.Map;
import java.util.Map;
public class ExampleHashMap {
public static void main(String[] args) {
// creating a HashMap
Map<String, Integer> map = new HashMap<>();
// adding elements
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
// accessing elements
int valorTwo = map.get("two");
System.out.println("Value associated with the key 'two': " + valueTwo);
// iterating over key-value pairs
for (Map.Entry<String, Integer> entry :map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
In the above example, a "HashMap" is created to store key-value pairs, where the keys are strings and the values are integers. The "put" method is used to add elements, and the "get" method is used to retrieve the value associated with a specific key. The "for" loop is used to iterate over all key-value pairs in the map.
It is important to note that the efficiency of "HashMap" is associated with the efficient distribution of keys in the hash table, which minimizes collisions. To ensure efficiency, it is common to override the "hashCode()" and "equals()" methods when using custom objects as keys.
Nenhum comentário:
Postar um comentário