Dart Set.identity()
Syntax & Examples


Set.identity constructor

The `Set.identity` constructor in Dart creates an empty identity Set.


Syntax of Set.identity

The syntax of Set.Set.identity constructor is:

Set.identity()

This Set.identity constructor of Set creates an empty identity Set.



✐ Examples

1 Adding numbers to an identity Set

In this example,

  1. We create a new empty identity Set called `numbers`.
  2. We add integers 1 and 2 to the `numbers` Set using the `add` method.
  3. We then attempt to add a duplicate element (1) to the `numbers` Set, but it doesn't get added because it's an identity Set.
  4. We print the `numbers` Set, which shows only distinct elements (1 and 2).

Dart Program

void main() {
  Set<int> numbers = Set.identity();
  numbers.add(1);
  numbers.add(2);
  numbers.add(1); // Adding duplicate element
  print(numbers); // Output: {1, 2}
}

Output

{1, 2}

2 Adding strings to an identity Set

In this example,

  1. We create a new empty identity Set called `words`.
  2. We add strings 'apple' and 'banana' to the `words` Set using the `add` method.
  3. We then attempt to add a duplicate element ('apple') to the `words` Set, but it doesn't get added because it's an identity Set.
  4. We print the `words` Set, which shows only distinct elements ('apple' and 'banana').

Dart Program

void main() {
  Set<String> words = Set.identity();
  words.add('apple');
  words.add('banana');
  words.add('apple'); // Adding duplicate element
  print(words); // Output: {apple, banana}
}

Output

{apple, banana}

Summary

In this Dart tutorial, we learned about Set.identity constructor of Set: the syntax and few working examples with output and detailed explanation for each example.