Set interface

PHOTO EMBED

Sun Dec 25 2022 20:54:50 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka #java #generics #set

//A Set is a collection of unique elements and all of its methods ensure this stays true. 
//The HashSet implementation has the best performance when retrieving or inserting elements but cannot guarantee any ordering among them.
//The TreeSet implementation does not perform as well on insertion and deletion of elements but does keep the elements stored in order based on their values (this can be customized).
//The LinkedHashSet implementation has a slightly slower performance on insertion and deletion of elements than a HashSet but keeps elements in insertion order.

Set<Integer> intSet = new HashSet<>();  // Empty set
intSet.add(6);  // true - 6  
intSet.add(0);  //  true - 0, 6 (no guaranteed ordering)
intSet.add(6);  //  false - 0, 6 (no change, no guaranteed ordering)
 
boolean isNineInSet = intSet.contains(9);  // false
boolean isZeroInSet = intSet.contains(0);  // true

// Assuming `intSet` has elements -> 1, 5, 9, 0, 23
for (Integer number: intSet) {
  System.out.println(number);
}
// OUTPUT TERMINAL: 5 0 23 9 1
content_copyCOPY