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,
- We create a new empty identity Set called `numbers`.
- We add integers 1 and 2 to the `numbers` Set using the `add` method.
- 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.
- 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,
- We create a new empty identity Set called `words`.
- We add strings 'apple' and 'banana' to the `words` Set using the `add` method.
- 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.
- 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.