Java HashSet MCQ Questions and Answers
Q. What is the purpose of the HashSet
class in Java?
A. To store a collection of unique elementsB. To sort elements in ascending order
C. To provide constant-time access to elements
D. To implement a stack data structure
Q. Which interface does HashSet
implement in Java?
A. Set
B.
List
C.
Queue
D.
Deque
Q. What is the time complexity of adding an element to a HashSet
in Java?
A. O(1)B. O(log n)
C. O(n)
D. O(n log n)
Q. How does HashSet
handle duplicate elements during addition?
A. It adds the duplicate elementB. It replaces the existing element
C. It throws an exception
D. It ignores the duplicate element
Q. What is the time complexity of removing an element from a HashSet
in Java?
A. O(1)B. O(log n)
C. O(n)
D. O(n log n)
Q. How does HashSet
handle null elements?
A. It allows multiple null elementsB. It allows only one null element
C. It throws an exception for null elements
D. It treats null as a regular element
Q. What is the default load factor of a HashSet
in Java?
A. 0.5B. 0.75
C. 1.0
D. It varies based on the JVM
Q. How can you iterate over the elements of a HashSet
in Java?
A. Using a for
loopB. Using an iterator
C. Using a
while
loopD. All of the above
Q. What is the output of new HashSet<>(List.of(1, 2, 2, 3, 4)).size()
in Java?
A. 4B. 5
C. It throws an exception
D. It depends on the JVM
Q. How can you create a HashSet
that is synchronized and thread-safe in Java?
A. By using the Collections.synchronizedSet()
methodB. By extending the
HashSet
class and overriding its methodsC. By using the
ConcurrentHashMap
classD. HashSet cannot be made thread-safe
Q. What is the output of the following code?
HashSet<String> colors = new HashSet<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); colors.add("Red"); for (String color : colors) { System.out.println(color); }A.
Red Green BlueB.
Red GreenC.
Green Blue RedD.
Blue Red Green