Sobes.tech
Junior

What is a Set in Java?

sobes.tech AI

Answer from AI

A Set in Java is a collection of unique elements that does not guarantee order.

Main characteristics:

  • Uniqueness: Cannot contain duplicates. If an attempt is made to add an existing element, the operation will be ignored (depending on the implementation).
  • No indexing: Elements are not accessible by index.
  • Interface: Part of the Java Collections Framework and extends the Collection interface.

Most commonly used implementations:

  • HashSet: The fastest implementation, based on a hash table. Does not guarantee element order.
  • LinkedHashSet: Maintains insertion order of elements, using a linked list in addition to a hash table.
  • TreeSet: Stores elements in sorted order (natural or by a specified comparator), based on a red-black tree.

Example of using HashSet:

// Creating a HashSet
Set<String> uniqueNames = new HashSet<>();

// Adding elements
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // This element will be ignored
uniqueNames.add("Charlie");

// Checking for an element
boolean containsBob = uniqueNames.contains("Bob"); // true

// Iterating over elements (order not guaranteed)
for (String name : uniqueNames) {
    System.out.println(name);
}

// Size of the Set
int size = uniqueNames.size(); // 3