Loading
Java - Set Interface-interview

Q1. What is the Set interface in Java and why is it used?

The Set interface in Java is part of the Collection Framework and is used to store a collection of unique elements. It does not allow duplicates, making it ideal for scenarios like storing IDs or email addresses.






Q2. What are the key differences between List and Set?
  • List: Allows duplicates, maintains insertion order.
  • Set: Does not allow duplicates, order is not guaranteed (except in special types like LinkedHashSet or TreeSet).





Q3. What are the main implementations of Set in Java?

The main ones are:

  • HashSet: Stores unique elements, unordered.
  • LinkedHashSet: Maintains insertion order.
  • TreeSet: Stores elements in sorted (natural) order.





Q4. How does HashSet ensure uniqueness of elements?

HashSet uses hashing internally. It relies on the hashCode() and equals() methods to ensure that no duplicate elements are stored.






Q5. Can we store null values in a Set?
  • HashSet & LinkedHashSet: Allow one null value.
  • TreeSet: Does not allow null because it needs to sort elements.