Junior — Middle
Could you list and describe possible implementations of the Set interface in your chosen programming language?
sobes.tech AI
Answer from AI
In Java, the Set interface represents a collection of unique elements. The main implementations of the Set interface include:
-
HashSet
- Based on a hash table.
- Fast access (add, remove, search operations — on average O(1)).
- Does not guarantee the order of elements.
-
LinkedHashSet
- Inherits from HashSet but maintains the insertion order of elements.
- Slightly slower than HashSet due to maintaining a linked list.
-
TreeSet
- Based on a red-black tree (a data structure for balanced search).
- Elements are stored in sorted order.
- Add, remove, search operations — O(log n).
Example usage:
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("apple"); // duplicate will not be added
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("apple");
linkedHashSet.add("banana");
Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
System.out.println("HashSet: " + hashSet);
System.out.println("LinkedHashSet: " + linkedHashSet);
System.out.println("TreeSet: " + treeSet);
}
}
Thus, the choice of implementation depends on the requirements for element order and performance.