1. What is a HashSet in Java?
Answer:
Explanation:
HashSet in Java is a collection that uses a hash table, providing efficient storage and retrieval.
2. What is the primary characteristic of a HashSet?
Answer:
Explanation:
HashSet stores unique elements only; it does not allow duplicates.
3. Which interface does HashSet implement?
Answer:
Explanation:
HashSet implements the Set interface.
4. How does HashSet store its elements?
Answer:
Explanation:
HashSet stores elements by using a hash table, where elements are placed according to their hash codes.
5. Can HashSet contain null values?
Answer:
Explanation:
HashSet can contain one null value.
6. What is the time complexity of basic operations such as add, remove, and contains in HashSet?
Answer:
Explanation:
Basic operations like add, remove, and contains have a constant time complexity O(1) in a HashSet.
7. How do you add elements to a HashSet?
Answer:
Explanation:
The add() method is used to add elements to a HashSet.
8. How do you check if a HashSet contains a specific element?
Answer:
Explanation:
The contains() method is used to check if an element exists in a HashSet.
9. What happens if you try to add a duplicate element to a HashSet?
Answer:
Explanation:
If a duplicate element is added to a HashSet, it is simply ignored.
10. How do you remove all elements from a HashSet?
Answer:
Explanation:
The clear() method is used to remove all elements from a HashSet, making it empty.
11. What happens when you iterate over a HashSet?
Answer:
Explanation:
Iterating over a HashSet does not guarantee any specific order of elements.
12. Can a HashSet be synchronized?
Answer:
Explanation:
A HashSet can be synchronized by wrapping it with Collections.synchronizedSet().
13. Is it possible to convert a HashSet to an ArrayList?
Answer:
Explanation:
A HashSet can be converted to an ArrayList by passing the set to the ArrayList constructor.
14. What constructor can be used to create a HashSet with a specified initial capacity?
Answer:
Explanation:
The HashSet(int capacity) constructor creates a HashSet with the specified initial capacity.
15. How can you ensure the elements of a HashSet are sorted?
Answer:
Explanation:
Elements in a HashSet cannot be sorted directly; however, you can convert the HashSet to a TreeSet to sort the elements.