Collections
Sets
Unique Members
A set literal <T>{...} stores unique values. Adding a duplicate is a no-op.
Program
Play the program to add a duplicate and a new color, then read the length.
sets.dart
Replay: real traced execution (multi-file project)
void main() {
var colors = <String>{'red', 'green'};
colors.add('red');
colors.add('blue');
print(colors.length);
}
colors ← {red, green}
1void main() {2 var colors = <String>{'red', 'green'};3 colors.add('red');values this step{red, green}colorscolors.add('red');
2var colors = <String>{'red', 'green'};3colors.add('red');4colors.add('blue');values this step{red, green}colorscolors ← {red, green, blue}
3colors.add('red');4colors.add('blue');5print(colors.length);values this step{red, green} → {red, green, blue}colorsprint(colors.length);
4 colors.add('blue');5 print(colors.length);6}output3values this step{red, green, blue}colors
Add Unique Colors
- Start with
redandgreen. - Adding
redagain changes nothing. - Adding
blueinserts a new unique value. - The final length is
3. | Action | Set contents | | --- | --- | | start |{red, green}| | addred|{red, green}| | addblue|{red, green, blue}|
set literal
`<String>{...}` declares an empty-or-seeded set.
uniqueness
Adding an existing element does not grow the set.
length
`length` reports the number of unique entries.
Exercise: sets.dart
Add a duplicate and a new value to a set, then print the final unique count