Logo

Programming-Idioms

  • C
  • Java
  • Scala

Idiom #34 Create a set of objects

Declare and initialize a set x containing unique objects of type T.

val x = Set[T]()

The default implementation of Set is a HashSet
import static java.util.Set.of;
import java.util.Set;
Set<T> x = of(a, b, c);
import java.util.Set;
import java.util.HashSet;
Set<T> x = new HashSet<T>();
x.add(a);
x.add(b);

T should override equals(), per the Set contract.
T should override hashCode(), per the HashSet contract.
import java.util.Set;
import java.util.HashSet;
Set<T> x = new HashSet<T>();

The type T must respect the equals() / hashcode() contract.
#include <unordered_set>
std::unordered_set<T, hasher, eq> x;

Using a custom hasher and eq (equality checking function)

New implementation...