Sets
Sets within the collections framework are the programmatic equivalent of mathematical sets. This means that they can store objects of a specific type while avoiding duplicates. In the same way, sets offer methods that will let you handle data as you would in mathematics. You can add objects to a set, check whether a set is empty, combine the elements of two sets to add all their elements into a single set, see what objects coincide with each other between two sets, and calculate the difference between two sets.
In the java.util.Sets
class, we find three interfaces used to represent sets: HashSet
, TreeSet
, and LinkedHashSet
. The differences between them are straightforward:
HashSet
will store data without guaranteeing the order of iteration.TreeSet
orders a set by value.LinkedHashSet
orders a set by arrival time.
Each of these interfaces is meant to be used under specific circumstances. Let's look at a couple of examples of sets, departing from...