HashSet & LinkedHashSet — Concept Check
Questions on HashSet & LinkedHashSet. Store unique elements with O(1) lookup using HashSet, or preserve insertion order with LinkedHashSet — both backed by the corresponding Map.
Questions in this quiz
8 questions on HashSet & LinkedHashSet — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A developer uses a HashSet to store user IDs for fast lookup. What happens if the hashCode() method of UserID class returns the same value for all instances?
- AHashSet will throw an exception during operations.
- BPerformance degrades as all elements hash to the same bucket.
- CDuplicate entries will be allowed in the HashSet.
- DHashSet will automatically rehash the elements.
2.You have a LinkedHashSet of URLs visited by a user. What will be the output if you convert it to a List and access the first element?
- AThe last URL visited by the user.
- BA random URL from the set.
- CThe first URL visited by the user.
- DThe URL with the highest hash code.
3.A HashSet contains several Point objects. What happens if you modify a Point's coordinates after adding it to the set?
- AThe Point may become unreachable in the set.
- BThe Point will be removed from the set.
- CThe set will throw a ConcurrentModificationException.
- DThe set will automatically update the Point's position.
4.Which of the following operations is NOT guaranteed to be O(1) on average for a HashSet?
- Aadd()
- Bremove()
- Ccontains()
- DIteration over elements
5.A developer needs to preserve the order of elements in a set while ensuring uniqueness. Which data structure should they use?
- AArrayList
- BLinkedHashSet
- CHashSet
- DTreeSet
6.What will be the output of the following code snippet? Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("apple"); System.out.println(set.size());
- A3
- B2
- C4
- D1
7.A developer believes LinkedHashSet is faster than HashSet because it maintains order. Is this true?
- ANo, maintaining order adds overhead to LinkedHashSet.
- BNo, both have the same performance characteristics.
- CYes, LinkedHashSet is optimized for speed.
- DYes, order maintenance improves lookup speed.
8.Why might using mutable objects as elements in a HashSet lead to unexpected behavior?
- AHashSet cannot store objects with mutable fields.
- BMutable objects automatically become immutable in a HashSet.
- CMutable objects can change hash codes, affecting element retrieval.
- DMutable objects are not allowed in HashSet.