This in an interesting Data Structure. It stores unsorted, unique values, distributed without any particular order. It’s up to the programmer to decide how elements will be sorted and why. Set can hold any type of the data from primitives to objects.
Methods
There is a collection of methods which should be implemented to make a Set. Please mind, that these are the basic ones, feel free to implement any other functions which comes handy for you.
- set.add(value): add new value to set
- set.has(value): tells if set contains given value
- set.remove(value): removes value from set
- set.clear(): removes all values from set
- set.union(set2): adds all unique values to set from set2
- set.is_subset(set2): tells if all values from set are present in set2
- set.intersection(set2): returns values present in both set and set2
- set.is_disjoint(set2): returns true when set and set2 doesn’t have any common values
Usages
Set is a proper choice when it comes to store a collection of values which have to be unique. Take the quiz for that instance. Many people can submit their answers, and during submission your program checks if answer already exists in a Set, so it won’t be duplicated. Or tickets to the concert of your favourite band. Everytime a bouncer scans the number from your pass, there is a Set of validated tickets which keeps track who has already entered the venue. Applications are basically countless.