Hash Map Flashcards
Show me how to create a hash map
Map<Integer, Integer> map = new HashMap<>();
Show me what import you need for a hash map
java.util.*
Show me how to store a key value pair?
map.put(key, value)
Show me how to get the value of a key?
map.get(key)
Will get the associated value
What is a hashmap?
A HashMap is a data structure that stores key-value pairs and allows for fast lookups, insertions, and deletions.
Best data structure?
Arrays or array lists
Why can the big O complexity sometimes be O(n)? And is that the worst case of a hashmap
Yes, big O worst case of hashmap is O(n)
It can get like that if too many elements hash to the same index, the hashmap degenerates into a linked list
What does put method do in a Hashmap?
put(key, value)
Updates the value if the key exists
What does get method do in a Hashmap?
get(key)
Gets the value of the key
What does entrySet do in a Hashmap?
Returns a set of all key-value pairs
What does values() do in a hashmap?
Return a collectio nof all values in the hash map
What does keySet() do in a hashmap?
Returns a set of all keys in the hashmap
How does a hash map work internally?
- Computes a hash using hashCode() from the key
- maps the hash to an index in an array (buckets)
- If collision occurs, uses a linked lists or uses a balanced tree to fix this
How is a hashmap different from a hashset?
Hashmaps store key value paris while hashsets store unique elements
- Keys are unique but values can repeat in a Hashmap