Set is another important Datastructure created in Java, just like List.
Set is same as List, except it dont contain duplicates, and dont maintain order.
As you remember, List can have duplicates & also maintains internal Order.
Set Types:
Below are the most used implementation classes of Set Interface.
- HashSet – HashTable implementation of Set Interface.
- TreeSet – Tree Implementation of Set Interface.
Simple Example of Set (using HashSet).,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<Integer> yearSet = new HashSet(); yearSet.add(2019); yearSet.add(2018); yearSet.add(2017); yearSet.add(2016); // Trying to insert a Duplicate Record... Not inserted.. yearSet.add(2019); System.out.println(yearSet); } } |
Result:
[2019, 2018, 2017, 2016]