Junior — Middle
Can you explain how the HashSet data structure works?
sobes.tech AI
Answer from AI
HashSet in Java is a data structure that stores unique elements without a specific order. It is based on HashMap, where elements act as keys, and values are placeholders.
Main features of HashSet:
- Fast access, addition, and removal of elements — operations are performed in approximately O(1).
- Does not allow duplicates.
- The order of elements is not guaranteed.
Example of usage:
import java.util.HashSet;
public class Example {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // will not be added again, as it already exists
for (String fruit : set) {
System.out.println(fruit);
}
}
}
In this example, "apple" will be added only once, even if you try to add it twice.