Java HashSet MCQ - Multiple Choice Questions and Answers

1. What is a HashSet in Java?

a) A dynamic array
b) A collection that uses a hash table for storage
c) A linked list
d) A data structure for key-value pairs

2. What is the primary characteristic of a HashSet?

a) Ordered elements
b) Duplicate elements
c) Sorted elements
d) Unique elements

3. Which interface does HashSet implement?

a) List
b) Map
c) Set
d) Queue

4. How does HashSet store its elements?

a) In index-based order
b) In a sequential list
c) Based on hash codes of the elements
d) In sorted order

5. Can HashSet contain null values?

a) Yes
b) No
c) Only one null value
d) Only if it's empty

6. What is the time complexity of basic operations such as add, remove, and contains in HashSet?

a) O(1)
b) O(log n)
c) O(n)
d) O(n^2)

7. How do you add elements to a HashSet?

a) add()
b) put()
c) insert()
d) append()

8. How do you check if a HashSet contains a specific element?

a) find()
b) search()
c) contains()
d) hasElement()

9. What happens if you try to add a duplicate element to a HashSet?

a) The element is added at the end
b) The element replaces the existing one
c) The duplicate is ignored
d) An exception is thrown

10. How do you remove all elements from a HashSet?

a) clear()
b) removeAll()
c) deleteAll()
d) empty()

11. What happens when you iterate over a HashSet?

a) The elements are returned in sorted order
b) The elements are returned in the order they were added
c) The order of elements is unpredictable
d) Elements are returned in reverse order

12. Can a HashSet be synchronized?

a) Yes
b) No
c) Only in multi-threaded applications
d) Only if it's empty

13. Is it possible to convert a HashSet to an ArrayList?

a) Yes
b) No
c) Only if it has less than 10 elements
d) Only if it's sorted

14. What constructor can be used to create a HashSet with a specified initial capacity?

a) HashSet(int capacity)
b) HashSet()
c) HashSet(Collection c)
d) HashSet(int capacity, float loadFactor)

15. How can you ensure the elements of a HashSet are sorted?

a) By using the sort() method
b) HashSet elements cannot be sorted
c) By converting it to a TreeSet
d) By using Collections.sort()

Comments