cloneSet<E> method
Return a deep-cloned Set.
When doTypedClone is true the returned set preserves element types and
performs typed cloning of elements. Typed cloning will throw UnsupportedTypedCloneException
if a nested Map is encountered.
On dynamic cloning preserves the concrete Set implementation (e.g. LinkedHashSet,
HashSet, UnmodifiableSetView).
Typed nested cloning will erase generics at runtime; the typed Set cloning implementation
relies on toSet() to preserve the runtime element type of the original set, but not underlying implementation.
Implementation
@override
Set<E> cloneSet<E>(Set<E> source) {
final isUnmodifiable = source is UnmodifiableSetView<E>;
final Set<E> cloned;
if (doTypedClone) {
cloned = source.toSet();
cloned.clear();
for (final e in source) {
cloned.add(_cloneValueTyped(e));
}
} else {
cloned = switch (source) {
LinkedHashSet<E>() => <E>{for (final e in source) cloneValue(e)},
HashSet<E>() => HashSet<E>.of(source.map((e) => cloneValue(e))),
_ => <E>{for (final e in source) cloneValue(e)},
};
}
return isUnmodifiable ? UnmodifiableSetView<E>(cloned) : cloned;
}