HashSet and HashMaps
What are the differences between HashSet and HashMap?
- Insertion: add() for HashSet; put() for HashMap - No duplicates for HashSet - Key and Value needed for insertion for HashMap - HashSet only needs value for insertion - Runtime: HashMap is faster
What are thecommon methods that each class supports for insertion and retrieval?
HashSet: .add, .contains, .clear, .remove, .contains HashMap: .put, .get, .isEmpty, .size, .remove, .containsKey, .containsValue
How do you iterate through all the keys in a HashMap?
Iterate through keys using keySet(). Iterate through values using values()
How do you iterate through all the elements in a HashSet?
Iterate with a for each loop
For HashMaps, what is the runtime difference between containsKey() and containsValue(), and why?
containsValue(): O(n) because all the values have to be iterated over containsKey(): O(1) because there is a key that is used to access value