HashSet<E> constructor

HashSet<E>()

A custom implementation of a hash set that implements the Set<E> interface.

This HashSet stores unique elements and provides constant-time operations for insertion, removal, and lookup in the average case.

It uses open addressing with chaining to resolve hash collisions: each bucket is a list of values (List<E>) that share the same hash index.

When the load factor (size / capacity) exceeds 0.75, the internal bucket array is resized to maintain efficiency.


⚙️ Design Highlights:

  • Uses _buckets: List<List<E>?> for collision handling
  • On collision: appends to the list in the corresponding bucket
  • Grows dynamically when usage exceeds load factor threshold

📦 Example Usage:

final set = HashSet<String>();
set.add('apple');
set.add('banana');
set.add('apple'); // Duplicate, ignored

print(set.contains('banana')); // true
print(set.length); // 2
print(set); // {apple, banana}

Creates an empty set with an initial capacity of 16.

Implementation

HashSet() : _capacity = _initialCapacity, _buckets = List.filled(_initialCapacity, null);