2. Sets- Nitin

What is a Set?

  • Collection that cannot contain duplicate elements
  • Models the mathematical set abstraction
  • No guarantees concerning the order of elements

Key Operations

  • add(E e): Adds element to the set if not already present
  • remove(Object o): Removes specified element if present
  • contains(Object o): Returns true if set contains the specified element
  • isEmpty(): Returns true if set contains no elements
  • size(): Returns the number of elements in the set
  • clear(): Removes all elements from the set

Key takeaways

  • NO DUPLICATES
  • No ORDER
  • Operations generally in O(1) for many set implementations

Example: Basic Set Operations

Set<String> fruits = new HashSet<>();
        
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple");  // Duplicate, won't be added!!!
System.out.println("Set after adding elements: " + fruits);

fruits.remove("Banana");
System.out.println("Set after removing 'Banana': " + fruits);

boolean containsOrange = fruits.contains("Orange");
System.out.println("Set contains 'Orange': " + containsOrange);

System.out.println("Size of Set: " + fruits.size());

System.out.println("Is Set empty: " + fruits.isEmpty());

fruits.clear();
System.out.println("Set after clearing: " + fruits);

System.out.println("Is Set empty after clear: " + fruits.isEmpty());
Set after adding elements: [Apple, Orange, Banana]
Set after removing 'Banana': [Apple, Orange]
Set contains 'Orange': true
Size of Set: 2
Is Set empty: false
Set after clearing: []
Is Set empty after clear: true