A set stores an unordered collection of unique values.
There is three implementations:
HashSetTreeSetLinkedHashSet| HashSet | TreeSet | LinkedHashSet | |
|---|---|---|---|
| Elements order | random | numerical or alpahbetical | order added |
| can store null value | Yes | No | Yes |
| add, remove, contains complexity | O(1) | O(log n) | O(1) |
Specify the data type of the elements and the type of set.
It can only contain reference type values.
// import the desired set type
import Java.util.Set;
import Java.util.HashSet;
import Java.util.TreeSet;
import Java.util.LinkedHashSet;
// Create a string HashSet
Set<String> colors = new HashSet<String>();
// Create an integer Tree set
TreeSet<Integer> myNumbers = new TreeSet<Integer>();
colors.add("red");
colors.add("red"); // duplicate is ignored
colors.remove("red");
colors.contains("red"); // true or false
colors.size()
for (String item : colors) {
System.out.println(item);
}
The set classe provide methods to perform mathematical operations on two different sets. Allowing to create or modify existing ones.
Use .addAll() to add all element of one set to another.
Set<String> colors = new HashSet<String>();
Set<String> favColors = new HashSet<String>();
// add colors to them
// add the favColors to the colors set
colors.addAll(favColors);
Use .retainAll() to keep only in a set, the value that are common to another one.
// only keep in colors, the ones that are also in favColors
colors.retainAll(favColors);
Use .removeAll() to remove from one set, the value that are also in another one.
// remove from colors, the one present in favColors
colors.removeAll(favColors);