Dart Collection: Dart Sets
In Dart, Sets are like exclusive guest lists for your programming party. They're a bit different from Lists – think of them as a set of unique invitations. Let's break it down.
1. No Duplicates: The VIP Rule
One special thing about Sets is that they don't allow duplicates. It's like saying, "Hey, each invitation is unique, and we don't want the same person at the party twice!"
Set<String> partyInvitations = {'Alice', 'Bob', 'Charlie', 'Alice'};
In this example, even though we tried to invite Alice twice, the Set is smart enough to only keep one copy. It's like having a VIP rule for uniqueness.
2. Adding Guests: The VIP Entrance
Adding new guests to a Set is like welcoming them through the VIP entrance. If they're already on the list, no worries – they won't get a duplicate invitation.
Set<String> partyInvitations = {'Alice', 'Bob', 'Charlie'};
partyInvitations.add('David');
Here, we're adding David to the set. The Set ensures that there's only one invitation for each guest, just like the VIP list at a fancy event.
3. Checking the Guest List: The Exclusive Club
Checking if someone is on the guest list is easy with Sets. It's like looking at the exclusive club roster to see if your friend made it in.
Set<String> partyInvitations = {'Alice', 'Bob', 'Charlie'};
bool isBobInvited = partyInvitations.contains('Bob');
The contains
method helps you check if Bob is part of the exclusive guest list. It's like ensuring only invited guests get through.
4. Removing Guests: The Elegant Exit
If someone needs to leave the party early, removing them from the Set is like ensuring they make an elegant exit. No fuss, just a smooth departure.
Set<String> partyInvitations = {'Alice', 'Bob', 'Charlie'};
partyInvitations.remove('Bob');
Here, Bob gracefully exits the party without leaving any trace in the Set. It's like having a well-maintained guest list.
Dart Sets are your elegant party invitations – unique, exclusive, and efficient. Whether you're adding new friends, checking the list, or gracefully removing guests, Sets have got the VIP treatment for your programming party!
Subscribe to my newsletter
Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by