Junior
How does the Set collection work in Java?
sobes.tech AI
Answer from AI
A Set in Java is a collection that does not contain duplicate elements. It is based on hash tables or balanced trees and provides:
- Uniqueness of elements: It guarantees that each element in the Set is present only once.
- No order: Most often, elements in a Set are not stored in a specific order (except for specific implementations like
LinkedHashSet). - Fast search, insertion, and deletion: Operations
add(),remove(),contains()usually have an average time complexity of O(1) forHashSet, assuming good hashing.
Main methods:
add(E element): Adds the specified element to the Set. If the element already exists, it returnsfalse, otherwisetrue.remove(Object o): Removes the specified element from the Set if it exists.contains(Object o): Checks for the presence of the specified element in the Set.size(): Returns the number of elements in the Set.isEmpty(): Checks if the Set is empty.
Most common implementations:
HashSet: Based on a hash table. Offers high performance for basic operations but does not guarantee element order.LinkedHashSet: Based on a hash table and linked list. Preserves the insertion order of elements.TreeSet: Based on a balanced tree (Red-Black Tree). Elements are stored in sorted order. Requires elements to implementComparableor provide aComparator.
The operation of HashSet is based on the hashCode() and equals() methods of objects added to the collection. When an element is added, its hash code is computed. Using this hash code, a "bucket" in the hash table is determined where the element might be placed. Then, in this bucket (which can be represented by a linked list or a tree in Java 8+), the equals() method is used to check for duplicates.
Example:
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // This element will not be added, as it already exists
System.out.println("Size of Set: " + uniqueNames.size()); // Will output 2
for (String name : uniqueNames) {
System.out.println(name); // Output order may be arbitrary
}
System.out.println("Contains Bob? " + uniqueNames.contains("Bob")); // Will output true
uniqueNames.remove("Alice");
System.out.println("Size after removal: " + uniqueNames.size()); // Will output 1
}
}