Sobes.tech
Junior

Name the main implementations of the Set interface in Java.

sobes.tech AI

Answer from AI

Main implementations of the Set interface in Java:

  • HashSet: Uses a hash table for storage. Does not guarantee order. Fast access O(1) on average.
  • LinkedHashSet: Extends HashSet but maintains a linked list of entries in insertion order. Iteration is in insertion order.
  • TreeSet: Stores elements in sorted order using a red-black tree. Requires elements to be Comparable or a Comparator to be provided. add, remove, contains are O(log n).
  • EnumSet: A specialized high-performance implementation for use with enum types. Elements must be of the same enum type.

Here's a brief comparison table:

Implementation Ordered? Allows null? Storage basis Performance (average case)
HashSet No Yes Hash table O(1)
LinkedHashSet Yes Yes Hash table + linked list O(1)
TreeSet Yes (natural or custom order) No Red-black tree O(log n)
EnumSet Yes (enum order) No Bit vectors (internal) Very high, effectively O(1)

In modern Java, choose based on whether order matters, whether nulls are allowed, and performance needs.