Logo

Programming-Idioms

  • Java
  • Pascal
  • Go

Idiom #34 Create a set of objects

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

x := make(map[T]bool)

There is no built-in Set type, but you can create a Map with key type T and boolean value (which will be ignored).
x := make(map[T]struct{})

The struct{} type is space efficient because it occupies zero bytes in memory.
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...